转载链接:http://blog.csdn.net/asukasmallriver/article/details/74356771?locationNum=2&fps=1
监视模块
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_num
p.print_callers(0.5, "sum_num")
# 查看test()函数中调用了哪些函数
p.print_callees("test")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
结果类似:
8 function calls in 0.042 seconds
Ordered by: cumulative time
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}
其中,输出每列的具体解释如下:
percall:(第一个percall)等于
percall:(第二个percall)即函数运行一次的平均时间,等于
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