使用cProfile分析Python程序性能

来源:互联网 发布:radeon pro 580windows 编辑:程序博客网 时间:2024/05/18 20:08

转:使用cProfile分析Python程序性能

监视模块

cProfile:基于lsprof的用C语言实现的扩展应用,运行开销比较合理,适合分析运行时间较长的程序,推荐使用这个模块;
profile:纯Python实现的性能分析模块,接口和cProfile一致。但在分析程序时增加了很大的运行开销。不过,如果你想扩展profiler的功能,可以通过继承这个模块实现;
使用cProfile进行性能分析,你可以在Python脚本中实现,也可以使用命令行执行:

if __name__ == "__main__":    import cProfile    # 直接把分析结果打印到控制台    cProfile.run("test()")    # 把分析结果保存到文件中    cProfile.run("test()", filename="result.out")    # 增加排序方式    cProfile.run("test()", filename="result.out", sort="cumulative")

使用命令行运行的方法基本一致,Bash代码如下:

# 直接把分析结果打印到控制台python -m cProfile test.py# 把分析结果保存到文件中python -m cProfile -o result.out test.py# 增加排序方式python -m cProfile -o result.out -s cumulative test.py

分析工具

使用cProfile分析的结果可以输出到指定的文件中,但是文件内容是以二进制的方式保存的,用文本编辑器打开时乱码。所以,Python提供了一个pstats模块,用来分析cProfile输出的文件内容。

import pstats# 创建Stats对象p = pstats.Stats("result.out")# strip_dirs(): 去掉无关的路径信息# sort_stats(): 排序,支持的方式和上述的一致# print_stats(): 打印分析结果,可以指定打印前几行# 和直接运行cProfile.run("test()")的结果是一样的p.strip_dirs().sort_stats(-1).print_stats()# 按照函数名排序,只打印前3行函数的信息, 参数还可为小数,表示前百分之几的函数信息 p.strip_dirs().sort_stats("name").print_stats(3)# 按照运行时间和函数名进行排序p.strip_dirs().sort_stats("cumulative", "name").print_stats(0.5)# 如果想知道有哪些函数调用了sum_nump.print_callers(0.5, "sum_num")# 查看test()函数中调用了哪些函数p.print_callees("test")

结果类似:

8 function calls in 0.042 seconds   Ordered by: cumulative time   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.000    0.000    0.042    0.042 test.py:5(<module>)        1    0.002    0.002    0.042    0.042 test.py:12(test)        2    0.035    0.018    0.039    0.020 test.py:5(sum_num)        3    0.004    0.001    0.004    0.001 {range}        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

其中,输出每列的具体解释如下:

    ncalls:表示函数调用的次数;    tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;    percall:(第一个percall)等于 tottime/ncalls    cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;    percall:(第二个percall)即函数运行一次的平均时间,等于 cumtime/ncalls    filename:lineno(function):每个函数调用的具体信息;

另外,上面分析的时候,排序方式使用的是函数调用时间(cumulative),除了这个还有一些其他允许的排序方式:calls, cumulative, file, line, module, name, nfl, pcalls, stdname, time等。

图形化工具

对于一些比较大的应用程序,如果能够将性能分析的结果以图形的方式呈现,将会非常实用和直观,常见的可视化工具有Gprof2Dot,visualpytune,KCacheGrind等,这里介绍一下Gprof2Dot的用法。
使用之前,你需要安装graphviz:

sudo apt-get install graphviz

然后下载Gprof2Dot:gprof2dot.py之后运行:

python gprof2dot.py -f pstats result.out | dot -Tpng -o result.png

结果如下:
这里写图片描述



参考文献:

Python 性能分析入门指南
检测Python程序执行效率及内存和CPU使用的7种方法
Python 代码性能优化技巧
关于Python Profilers性能分析器
The Python Profilers