profile[计算方法耗时模块]用法

#安装

pip install Profile

#引用方法

import Profile

#用法(Profile.run("方法名"))

Profile.run(“function”)

#运行结果字段展示

ncalls

函数的被调用次数

tottime

函数总计运行时间,除去函数中调用的函数运行时间

percall

函数运行一次的平均时间,等于tottime/ncalls

cumtime

函数总计运行时间,含调用的函数运行时间

percall

函数运行一次的平均时间,等于cumtime/ncalls

filename:lineno(function)

函数所在的文件名,函数的行号,函数名

#然后可以结合pstats模块对函数消耗时间模块进行排序及处理

profile.run("foo()", "记录文件")

#结果保存到文件

p = pstats.Stats("prof.txt")

#结果百分之十然后按time字段排名

p.sort_stats(".1","time").print_stats()

#展示按time字段排名结果百分之十

 

p.sort_stats("time",".1").print_stats()

#pstats用法

strip_dirs()

用以除去文件名前名的路径信息。

add(filename,[…])

把profile的输出文件加入Stats实例中统计

dump_stats(filename)

把Stats的统计结果保存到文件

sort_stats(key,[…])

最重要的一个函数,用以排序profile的输出

sort_stats可接受的参数:

‘ncalls’

被调用次数

‘cumulative’

函数运行的总时间

‘file’

文件名

‘module’

文件名

‘pcalls’

简单调用统计(兼容旧版,未统计递归调用)

‘line’

行号

‘name’

函数名

‘nfl’

Name/file/line

‘stdname’

标准函数名

‘time’

函数内部运行时间(不计调用子函数的时间)

#还可以结合Hotshot模块进行分析

       import hotshot

       import hotshot.stats

       prof = hotshot.Profile("hs_prof.txt", 1)

       prof.runcall(foo)

       prof.close()

       p = hotshot.stats.load("hs_prof.txt")

       p.print_stats()

原文地址:https://www.cnblogs.com/zhangtebie/p/11185787.html