1. 装饰器代码
def do_profile(func):
def wrapper(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
func(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = pstats.SortKey.TIME # 根据tottime降序, 其他指标看源码枚举
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return wrapper
2. 装饰器使用
这样用方便一些
@do_profile # 使用注解(误)
def your_func():
do_your_thing()
if __name__ == '__main__':
your_func()
3. 输出
列名 含义
ncalls 表示函数调用的次数
tottime 表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间
percall(第一个) 等于 tottime/ncalls
cumtime 表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间
percall(第二个) 即函数运行一次的平均时间,等于 cumtime/ncalls
filename:lineno 每个函数调用的具体信息,一般指向函数名