cProfile——Python性能分析工具
摘录:
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, timepstats模块还支持交互式

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, timepstats模块还支持交互式

















