ero*_*gol 27 python performance profiling
在我的源代码中,我尝试捕获并测量Python中段的时间释放.如何以方便的方式精确测量该段传递时间?
Luk*_*raf 40
使用分析器.
Python cProfile
包含在标准库中.
要获得更方便的方法,请使用该包profilestats
.然后你可以使用装饰器来装饰你想要分析的功能:
from profilestats import profile
@profile
def my_function(args, etc):
pass
Run Code Online (Sandbox Code Playgroud)
这将导致在STDOUT上打印这样的摘要:
6 function calls in 0.026 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.026 0.026 some_code.py:3(some_func)
2 0.019 0.010 0.026 0.013 some_code.py:9(expensive_func)
2 0.007 0.003 0.007 0.003 {range}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Run Code Online (Sandbox Code Playgroud)
然而,更有用的信息是在cachegrind.out.profilestats
生成的文件中.您可以使用可以显示cachegrind统计信息的工具打开此文件,例如RunSnakeRun,并且可以轻松(或更轻松)读取调用堆栈的可视化,如下所示:
更新:拉取请求profilestats
和pyprof2calltree
已合并,因此它们现在也支持Python 3.x.