仅是为了改进@Joe Kington的上述答案。
对于 Python 3.x ,请使用 line_profiler :
安装:
pip install line_profiler
使用方法:
假设你有一个程序 main.py
,其中包含你想要针对时间进行性能分析的函数 fun_a()
和 fun_b()
;你需要在函数定义之前加上装饰器 @profile
。例如:
@profile
def fun_a():
@profile
def fun_b():
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包解析分析器的结果。使用它,我们可以获得逐行所需的绘图:
![plot](https://github.com/pra-dan/TAMPPA/raw/master/resources/mem_res.png)
pstats.print_callers
感兴趣。这里有一个例子:http://www.doughellmann.com/PyMOTW/profile/。 - Muhammad Alkarouri