如何找出每行Python代码的执行时间。
line_profiler 适用于 ipython,但不适用于 jupyter Notebook。我尝试将 @profile 添加到我的函数中,但它给出错误,指出名称“profile”未定义。 有一种方法可以通过 time.time() 来做到这一点,但我想知道是否有任何内置的分析函数可以分析函数的每一行并显示执行时间。
def prof_function():
x=10*20
y=10+x
return (y)
您可以在jupyter笔记本中使用
line_profiler
。
pip install line_profiler
%load_ext line_profiler
prof_function
,如您的示例所示。%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)
请注意,您可以分析调用层次结构中的任何函数,而不仅仅是顶部函数。如果您要分析的函数不在笔记本中,则必须将其导入。不幸的是,您只能分析从源代码运行的函数,而不能分析从您安装的库运行的函数(除非它们是从源代码安装的)。
示例:
import numpy as np
def sub_function():
a = np.random.random((3, 4))
x = 10 * a
return x
def prof_function():
y = sub_function()
z = 10 + y
return z
%lprun -f prof_function prof_function()
的输出:
Timer unit: 1e-09 s
Total time: 3.2e-05 s
File: /var/folders/hh/f20wzr451rd3m04552cf7n4r0000gp/T/ipykernel_51803/3816028199.py
Function: prof_function at line 6
Line # Hits Time Per Hit % Time Line Contents
==============================================================
6 def prof_function():
7 1 29000.0 29000.0 90.6 y = sub_function()
8 1 3000.0 3000.0 9.4 z = 10 + y
9 1 0.0 0.0 0.0 return z
%lprun -f sub_function prof_function()
的输出:
Timer unit: 1e-09 s
Total time: 2.7e-05 s
File: /var/folders/hh/f20wzr451rd3m04552cf7n4r0000gp/T/ipykernel_51803/572113936.py
Function: sub_function at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def sub_function():
2 1 13000.0 13000.0 48.1 a = np.random.random((3, 4))
3 1 14000.0 14000.0 51.9 x = 10 * a
4 1 0.0 0.0 0.0 return x
更多详细信息请参阅这篇不错的博客文章。
为了获取每行的执行时间并获得漂亮的颜色编码热图,我使用了这个漂亮的 ipython magic.... https://github.com/csurfer/pyheatmagic
安装:
pip 安装 py-heat-magic
要分析笔记本中的每一行:
%load_ext heat
在第二个单元格顶部的第一行输入:
%%heat
如果您的代码超过 2000 行,您可能会遇到问题。
只是@S.A.的回答的总结
!pip install line_profiler
%load_ext line_profiler
def func():
print('hi')
%lprun -f func func()
安装线路分析仪
conda install line_profiler
更多信息请参见 http://mortada.net/easily-profile-python-code-in-jupyter.html