kaituorensheng

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

运行结果

结果分析
    执行了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 -c "import pstats; p=pstats.Stats(\'del.out\'); p.sort_stats(\'time\').print_stats()"

sort_stats支持以下参数:

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

 

pstats模块还支持交互式

分类:

技术点:

相关文章:

  • 2021-10-14
  • 2021-09-09
  • 2021-09-09
  • 2021-12-15
  • 2021-11-02
  • 2021-09-29
  • 2021-11-07
猜你喜欢
  • 2021-11-07
  • 2021-11-07
  • 2021-05-18
  • 2021-09-19
  • 2021-09-19
  • 2021-12-08
  • 2021-10-08
相关资源
相似解决方案