cProfile——Python性能分析工具

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

 例子python

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,按着运行函数名字排序为结果输出。spa

运行脚本code

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

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

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支持如下参数:class

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

 

pstats模块还支持交互式

相关文章
相关标签/搜索