如何在 jupyter notebook 5 中逐行分析 python 3.5 代码

How to profile python 3.5 code line by line in jupyter notebook 5

如何找出每行 python 代码所用的执行时间。

line_profiler 适用于 ipython 但不适用于 jupyter notebook。我尝试将 @profile 添加到我的函数中,但它给出了错误提示 name 'profile' is not defined。 time.time() 有一种方法可以做到这一点,但我想知道是否有任何内置的分析功能可以分析我的函数的每一行并显示执行时间。

def prof_function():
    x=10*20
    y=10+x
    return (y)

安装线路分析器

conda install line_profiler

有关 http://mortada.net/easily-profile-python-code-in-jupyter.html

的更多信息

您可以在 jupyter notebook 中使用 line_profiler

  1. 安装它:pip install line_profiler
  2. 在你的 jupyter notebook 中,调用:%load_ext line_profiler
  3. 按照您的示例定义函数 prof_function
  4. 最后简介如下:%lprun -f prof_function prof_function()

这将提供输出:

Timer unit: 1e-06 s

Total time: 3e-06 s
File: <ipython-input-22-41854af628da>
Function: prof_function at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def prof_function():
     2         1          1.0      1.0     33.3      x=10*20
     3         1          1.0      1.0     33.3      y=10+x
     4         1          1.0      1.0     33.3      return (y)

为了获得每一行的执行时间并获得漂亮的彩色编码热图,我使用了这个漂亮的 ipython 魔法.... https://github.com/csurfer/pyheatmagic

安装:

pip install py-heat-magic

分析笔记本中的每一行:

  • 复制你的笔记本。
  • 合并所有单元格(突出显示所有单元格并按 shift-m)
  • 在顶部创建一个新单元格
  • 输入

%load_ext heat

在第二个单元格的顶部,在第一行输入:

%%heat  

如果您的代码超过 2000 行,您可能会遇到问题。

只是@S.A.的回答的总结

!pip install line_profiler
%load_ext line_profiler

def func():
    print('hi')

%lprun -f func func()