如何找出每一行python代码所占用的执行时间。
line_profiler适用于ipython,但不适用于jupyter笔记本。我尝试将@profile添加到我的函数中,它会出现错误,即名称'profile‘未定义。有一种方法可以通过time.time()来完成,但我想知道是否有内置的分析函数可以对我的函数的每一行进行分析并显示执行时间。
def prof_function():
x=10*20
y=10+x
return (y)
发布于 2018-04-13 19:39:29
您可以在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)
发布于 2018-09-22 23:46:49
为了获得每一行的执行时间并得到一个漂亮的彩色编码热图,我使用了这个很好的ipython魔术.https://github.com/csurfer/pyheatmagic
安装:
pip安装py-热魔术
要详细描述笔记本中的每一行:
%load_ext heat
在第二个单元格的顶部,在第一行输入以下内容:
%%heat
如果您有超过2000行代码,您可能会有问题。
发布于 2020-05-13 08:34:57
只是@S.A.答复的摘要
!pip install line_profiler
%load_ext line_profiler
def func():
print('hi')
%lprun -f func func()
https://stackoverflow.com/questions/44734297
复制相似问题