Python 中如何做性能分析(Profile)?
Python 性能分析用内置 cProfile 模块:python -m cProfile script.py 查看各函数耗时和调用次数。line_profiler 逐行分析。本文介绍各种工具。
用内置的 cProfile 模块:python -m cProfile myscript.py 就能输出每个函数的调用次数和耗时,找出性能瓶颈。需要逐行分析用第三方库 line_profiler。
方法一:命令行运行
python -m cProfile myscript.py
输出示例:
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 myscript.py:1(<module>)
500 0.045 0.000 0.045 0.000 myscript.py:10(process)
...
ncalls:调用次数tottime:该函数自身耗时(不含子调用)cumtime:累计耗时(含子调用)
方法二:代码中调用
import cProfile
cProfile.run('my_function()')
方法三:保存结果后用 pstats 排序
import cProfile
import pstats
cProfile.run('my_function()', 'profile_stats')
p = pstats.Stats('profile_stats')
p.sort_stats('cumulative').print_stats(20) # 按累计耗时排前 20
p.sort_stats('time').print_stats(20) # 按自身耗时排前 20
逐行分析:line_profiler
pip install line_profiler
在要分析的函数上加 @profile 装饰器,然后:
kernprof -l -v myscript.py
观测云对照
生产环境的性能分析不适合用 cProfile(开销大且只在单次运行时有效)。观测云 APM 通过 Java/Python/Go 探针持续监控每个接口的响应时间和方法级耗时,火焰图直观展示瓶颈,适合生产环境长期使用。
常见问题(FAQ)
Q:cProfile 会影响程序性能吗?
A:会。cProfile 会在每个函数调用时记录统计信息,总体增加约 10%-30% 的开销。只用于开发和测试。
Q:cProfile 和 timeit 有什么区别?
A:cProfile 告诉你哪里慢(哪些函数耗时多),timeit 告诉你有多快(精确测量某段代码的执行时间)。先用 cProfile 找瓶颈,再用 timeit 精确对比优化效果。
Q:如何可视化 cProfile 结果?
A:用 snakeviz 或 gprof2dot 将结果转为交互式图表,更直观。