Python标准库中提供了三种用来分析程序性能的模块,分别是
cProfile
,
profile
和
hotshot
,另外还有一个辅助模块stats。这些模块提供了对Python程序的确定性分析功能,同时也提供了相应的报表生成工具,方便用户快速地检查和分析结果,我们这里仅展示前两者的使用方法。
1、安装
由于以上三个模块都是本身集成在Python源代码中,所以不用特意安装,适合在权限不够的服务器上测试代码性能,使用时直接 import 就行。
2、cProfile测试方法
cProfile是基于lsprof的用C语言实现的扩展应用,运行开销比较合理,适合分析运行时间较长的程序,推荐使用这个模块。
2.1、在Python脚本中运行
def your_func():
.....
if __name__ == "__main__":
import cProfile
# 注意:运行的函数名要使用字符串的形式且带括号
# 直接把分析结果打印到控制台
cProfile.run('your_func()')
# 把分析结果保存到文件中
cProfile.run("your_func()", filename="result.out")
# 增加排序方式
cProfile.run("your_func()", filename="result.out", sort="cumulative")
运行结果类似下图:
显示结果列含义如下:
列名 | 含义 |
---|---|
ncalls | 表示函数调用的次数 |
tottime | 表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间 |
percall | (第一个percall)等于 tottime/ncalls |
cumtime | 表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间 |
percall | (第二个percall)即函数运行一次的平均时间,等于 cumtime/ncalls |
filename:lineno(function) | 每个函数调用的具体信息,一般指向函数名 |
2.2、在终端(bash)中运行
# 直接把分析结果打印到控制台
python -m cProfile test.py
# 把分析结果保存到文件中
python -m cProfile -o result.out test.py
# 增加排序方式
python -m cProfile -o result.out -s cumulative test.py
3、Profile测试方法
profile是纯Python实现的性能分析模块,接口和cProfile一致。但在分析程序时增加了很大的运行开销。不过,如果你想扩展profiler的功能,可以通过继承这个模块实现。
def your_func():
.....
if __name__ == "__main__":
from cProfile import Profile
# 注意:运行的函数名不需要加括号
prof = Profile()
prof.runcall(your_func)
prof.print_stats()
其运行结果和含义和cProfile模块一致,这里就不再展示。
参考文献
https://blog.csdn.net/asukasmallriver/article/details/74356771