cProfile和profile模块如何进行性能剖析?
请介绍Python中cProfile和profile模块的用途、区别以及如何使用。如何分析函数级别的调用次数、耗时,以及如何可视化剖析结果?
回答
小字辈
cProfile和profile是Python内置的性能剖析工具,用于统计函数调用次数和耗时。
区别:
cProfile(C扩展实现),开销小,适合生产环境profile(纯Python实现),开销大,但可扩展(可自定义子类)- 两者接口完全一致
基本用法:
import cProfile
import pstats
# 方式1:模块方式
# python -m cProfile -o output.prof my_script.py
# 方式2:编程方式
profiler = cProfile.Profile()
profiler.enable()
# 要分析的代码
result = sum(range(1000000))
profiler.disable()
# 统计输出
pstats.Stats(profiler).sort_stats('cumtime').print_stats(10)
排序选项:
cumtime: 累计耗时tottime: 自身耗时(不含子调用)ncalls: 调用次数
可视化工具:
- snakeviz:
pip install snakeviz,生成交互式火焰图 - gprof2dot: 生成函数调用图(SVG/PNG)
- py-spy: 采样式剖析器,无需修改代码
注意:cProfile会增加约10-20%的运行开销,生产环境建议使用采样式工具(如py-spy)。