只是为了改善@Joe Kington的上述答案。
对于Python 3.x,请使用line_profiler:
安装:
pip install line_profiler
用法:
假设您具有该程序main.py
及其中的功能fun_a()
,fun_b()
并且要针对时间进行分析;您将需要@profile
在函数定义之前使用装饰器。例如
@profile
def fun_a():
#do something
@profile
def fun_b():
#do something more
if __name__ == '__main__':
fun_a()
fun_b()
可以通过执行shell命令来分析程序:
$ kernprof -l -v main.py
可以使用获取参数 $ kernprof -h
Usage: kernprof [-s setupfile] [-o output_file_path] scriptfile [arg] ...
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-l, --line-by-line Use the line-by-line profiler from the line_profiler
module instead of Profile. Implies --builtin.
-b, --builtin Put 'profile' in the builtins. Use 'profile.enable()'
and 'profile.disable()' in your code to turn it on and
off, or '@profile' to decorate a single function, or
'with profile:' to profile a single section of code.
-o OUTFILE, --outfile=OUTFILE
Save stats to <outfile>
-s SETUP, --setup=SETUP
Code to execute before the code to profile
-v, --view View the results of the profile in addition to saving
it.
结果将在控制台上显示为:
Total time: 17.6699 s
File: main.py
Function: fun_a at line 5
Line # Hits Time Per Hit % Time Line Contents
==============================================================
5 @profile
6 def fun_a():
...
编辑:探查器的结果可以使用TAMPPA包进行解析。使用它,我们可以逐行获得所需的图
pstats.print_callers
。这里有一个例子。