Python性能优化资源汇总(持续更新) | Yet Another Thoughts
性能分析工具
自带干粮——profile, cProfile, hotshot
####profile/cProfile
profile是python的标准库,而cProfile是对应的C扩展。它们的reference点击这里。cProfile/profile在py2与py3中都可以使用。
可以在代码中使用cProfile:
import cProfile#以下调用运行函数somefunc(),并将相关数据记录到log_file.pyprofcProfile.run('somefunc()', 'log_file.pyprof')小程序也可以直接通过命令行调用cProfile模块执行:
python -m cProfile -o profile_data.pyprof script_to_profile.pyhotspot
hotshot是高性能的Profiling数据采集工具,其运行时对程序效率的影响很小,但会产生巨大的运行记录,分析也比较慢。Python 3中并没有它,若无特殊需求,请使用cProfile。示例代码:
import hotspotprofiler = hotspot.Profile('hotspot.log')profiler.run('trackStereo.solveStereoNew()')其他工具
这里介绍了若干个可视化的性能分析工具,比如:
- Gprof2Dot 将多种Profiler的数据转换成Graphviz可处理的图像表述。
- RunSnakeRun使用wxPython将Profiler数据可视化,还可以分析内存占用。
- KCacheGrind是Linux中常用的profiling visualization软件。
Python代码静态分析工具
Python code analysis tools—An overview介绍与比较了若干python代码静态分析工具,包括但不仅限于: