用法:
python -m cProfile filename.py
结果:
ncalls tottime percall cumtime percall filename:lineno(function)
ncalls: 该函数被调用的次数
tottime: 该函数的总耗时,子函数的调用时间不计算在内
percall: tottime / ncalls
cumtime: 该函数加上其所有子函数的总耗时
percall: cumtime / ncalls
使用下面的命令把结果保存在一个文件里
python -m cProfile -o result filename.py
然后使用pstats来格式化显示结果
python -c "import pstats; pstats.Stats('result').sort_stats(-1).print_stats()"
另外,我们也可以在代码里直接嵌入代码来使用cProfile和pstats模块,这样在程序退出时就会自动生成分析结果并打印,如下:
# 主代码def test(): pass import cProfile cProfile.run("test()", "result") import pstats pstats.Stats('result').sort_stats(-1).print_stats()
与cProfile相比,Line Profiler的结果更加直观,它可以告诉你一个函数中每一行的耗时。Line Profiler并不在标准库中,需要用pip来安装
pip install line_profiler
Line Profiler的使用方法与cProfile类似,同样建议为其创建decorator或是contextmanager来方便使用。