如何在Python中使用cProfile性能分析工具

如何在Python中使用cProfile性能分析工具?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Python自带了几个性能分析的模块:profile、cProfile和hotshot,使用方法基本都差不多,无非模块是纯Python还是用C写的。本文介绍cProfile。

例子

import time
def func1():
  sum = 0
  for i in range(1000000):
    sum += i
def func2():
  time.sleep(10)

func1()
func2()

运行

python -m cProfile del.py

运行结果

如何在Python中使用cProfile性能分析工具

结果分析

执行了6个函数,总共花费了10.138s,按着运行函数名字排序为结果输出。

运行脚本

python -m cProfile -o del.out del.py

这里以模块方式直接保存profile结果,可以进一步分析输出结果,运行

python -c "import pstats; p=pstats.Stats('del.out'); p.print_stats()"

结果(随机)

如何在Python中使用cProfile性能分析工具

可以设置排序方式,例如以花费时间多少排序

python -c "import pstats; p=pstats.Stats('del.out'); p.sort_stats('time').print_stats()"

如何在Python中使用cProfile性能分析工具

sort_stats支持以下参数:

calls, cumulative, file, line, module, name, nfl, pcalls, stdname, time

pstats模块还支持交互式

如何在Python中使用cProfile性能分析工具

看完上述内容,你们掌握如何在Python中使用cProfile性能分析工具的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!