性能分析(Profiling)可用于分析程序的运行时间主要消耗在何处,以便有效优化程序的运行效率。php
Profiling可分为两步,一是运行程序收集程序不一样部分运行时间的数据,二是数据的可视化和分析。html
目录[隐藏] |
Python的cProfile模块可用于数据采集,适用于Python 2和Python 3。其调用方法很简单:python
import cProfile# 如下调用将运行函数somefunc(),并将相关数据记录到log_file.pyprof cProfile.run('somefunc()', 'log_file.pyprof')
更多信息请参考Python Profiler文档。linux
有些小程序也能够直接从命令行调用cProfile模块执行[1]:小程序
python -m cProfile -o profile_data.pyprof script_to_profile.py
hotshot是高性能的Profiling数据采集工具,其运行时对程序效率的影响很小,但会产生巨大的运行记录,分析也比较慢。[2] Python 3中没有hotshot。故如无特殊需求,请使用cProfile。bash
import hotshot profiler = hotshot.Profile("hotshot.log") profiler.run('trackStereo.solveStereoNew()')
Gprof2Dot可将多种Profiler的数据转成Graphviz可处理的图像表述。配合dot命令,便可获得不一样函数所消耗的时间分析图。以处理cProfile的记录为例[3]:函数
# 运行程序记录数据: # python -m cProfile -o profile_data.pyprof path/to/your/script arg1 arg2 # profile_data.pyprof是获取的数据;dot命令须要安装Graphviz才能用 gprof2dot.py -f pstats profile_data.pyprof | dot -Tpng -o output.png
RunSnakeRun是个Python脚本,使用wxPython将Profiler数据可视化,效果如图。工具
RunSnakeRun还可分析内存占用,但仍处于实验阶段。[4]性能
KCacheGrind是Linux中经常使用的profiling visualization软件,其默承认处理valgrind的输出。经过一些脚本也能够让其分析cProfile或hotshot记录下的数据。优化
处理cProfile的数据可以使用pyprof2calltree:
# 运行程序记录数据: # python -m cProfile -o profile_data.pyprof path/to/your/script arg1 arg2 # 使用pyprof2calltree处理数据并自动调用KCacheGrind pyprof2calltree -i profile_data.pyprof -k
处理hotshot的数据可以使用KCacheGrind中的hotshot2calltree命令:
# 使用hotshot2calltree处理数据,完成后需手动在KCacheGrind中打开输出文件 hotshot2calltree hotshot.log -o hs_calltree.log