Ase*_*eem 5 python profiling python-3.x jupyter-notebook
如何找出每行python代码花费的执行时间。
line_profiler可用于ipython,但不适用于jupyter笔记本。我尝试将@profile添加到我的函数中,它给出错误消息,提示未定义名称'profile'。有一种方法可以通过time.time()来完成,但是我想知道是否有任何内置的性能分析函数可以对函数的每一行进行配置并显示执行时间。
def prof_function():
x=10*20
y=10+x
return (y)
Run Code Online (Sandbox Code Playgroud)
S.A*_*.A. 30
您可以line_profiler
在 jupyter 笔记本中使用。
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)
Run Code Online (Sandbox Code Playgroud)
Tho*_* G. 15
只是@SA 回答的摘要
!pip install line_profiler
%load_ext line_profiler
def func():
print('hi')
%lprun -f func func()
Run Code Online (Sandbox Code Playgroud)
为了获得每行的执行时间并获得漂亮的彩色编码热图,我使用了这个漂亮的ipython魔术。... https://github.com/csurfer/pyheatmagic
安装:
点安装py-heat-magic
要分析笔记本中的每一行:
%load_ext heat
在第二个单元格的顶部的第一行中输入以下内容:
%%heat
Run Code Online (Sandbox Code Playgroud)
如果您有2000行以上的代码,则可能会遇到问题。