剖面仪

这个 剖面仪 窗格递归地确定文件中调用的每个函数和方法的运行时和调用次数,将每个过程分解为其最小的单个单元。这使您可以轻松地识别代码中的瓶颈,将您指向对优化最关键的确切语句,并测量后续更改后的性能增量。

Spyder Profiler pane, displaying a list of functions and their execution time

运行Profiler

您可以使用Profiler路径框(窗格左上角)右侧的“打开”按钮浏览文件,这将自动对此文件运行性能分析。

Spyder Profiler pane, showing browsing a file and running profiler

您可以在窗格的路径框中手动输入路径,然后通过按对文件运行分析 Profile 在“探查器”窗格中。

还可以对当前在中打开的文件运行分析 编辑 通过单击 Run ‣ Profile 在菜单栏中,或使用可配置的快捷键 (F10 默认情况下)。

Spyder Profiler pane, showing running profiler from menu bar

如果要取消正在进行的运行,请单击 Stop 按钮,如果由于任何原因分析失败, Output 将显示对话框,指示发生的错误。

通过双击探查器中的项目,您将转到 编辑 它就是在那里命名的。

Spyder Profiler pane, showing opening a file when clicking on its analysis

您可以通过单击名称左侧的下拉箭头来增加为特定对象显示的级别数,并使用左上角的按钮展开/折叠所有项目。

Spyder Profiler pane, showing dropdown arrows and buttons for expanding and collapsing

通过单击下拉菜单或按下 Down Arrow 在FileName字段中键入,您可以调用以前配置文件的路径。

Spyder Profiler pane, showing dropdown of previous profiled files

最后,您可以将给定运行的数据作为文件保存到磁盘上,使用 .Result 扩展使用 Save data 按钮。方法加载该文件,以便与同一文件的上一次运行进行比较。 Load data 按钮。要删除加载的数据,请单击 Clear comparison 按钮。

Spyder Profiler pane, showing running profiler from menu bar

解读结果

结果按函数/方法/语句进行细分,每个子元素层次化地列在调用它们的顶级项下。 Total Time 是由指定项和每个“下面”函数( i.e. 呼叫者)它,而 Local Time 仅统计在特定可调用对象自己的作用域中花费的时间。这个 Calls 列显示指定对象在其父调用函数内(或在 __main__ 作用域,如果是顶级对象)。最后,数字中的数字 Diff 如果加载了比较,则会显示这三个值中每一个的列,并指示每个测量值之间的差值。

Profiler with a comparison loaded, displaying the time deltas between two runs

例如,假设您运行 Profiler 在调用函数的文件上 sleep_wrapper() 这反过来又被称为 sleep() 函数,并且 sleep_wrapper() 函数总共运行3.87ms,其中3.86ms用于执行 sleep() 函数。因此,如果 sleep() 它本身不叫其他任何东西,它的 Total TimeLocal Time 两者都是相同的,在3.87毫秒处。与此同时, Total Timesleep_wrapper() 将是3.86毫秒,但是 Local Time 只有0.01ms,因为睡觉是在 sleep() 它调用的函数。

探查器插件

您可以安装另外两个插件,以在Spyder中启用其他类型的分析。首先,Spyder Line Profiler允许您单独对代码的每一行进行基准测试。要了解更多信息,请访问 spyder-line-profiler git repository

Spyder Profiler pane, displaying a list of functions and their execution time

其次,Spyder Memory Profiler测量代码的内存使用情况。有关更多信息,请访问 spyder-memory-profiler git repository

Spyder Profiler pane, displaying a list of functions and their execution time