Python性能分析

来源:互联网 发布:计算机网络就业 知乎 编辑:程序博客网 时间:2024/05/19 12:14

Python的自带性能分析工具的使用总结。

cProfile

cProfile是Python解释器默认的性能分析器,它只测量CPU时间而不去关心内存等信息。


haha

其中,第一列表示有 39986次函数调用,其中23340次原生调用(不涉及递归)。

下面是具体的细节:

  • ncalls表示函数调用的次数,如果有两个数字,第一个是总调用次数,第二个是原生调用次数。

  • tottime表示函数内部消耗时间,不包括调用其它函数的时间。

  • percalltottime除以ncalls,表示一个函数每次调用的平均时间。

  • cumtime是之前所有子函数消耗时间的累计和(也包含递归调用)。

  • percallcumtime除以原生调用的数量,表示到该函数调用时,每个原生调用平均消耗时间。

  • filename:lineno(function)显示了被分析函数所在文件名、行号和函数名。

基本API如下:

class Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)#返回一个类,可以提供自定义函数计时,必须是一个返回当前时间的函数。如果数字是整数,timeunit 指定一个乘数表示换算成秒的系数。例如,如果定时器返回以毫秒为单位测量的时间,则timeunit就是.001enable()#Start collecting profiling data.disable()#Stop collecting profiling data.create_stats()#Stop collecting profiling data and record the results internally as the current profile.#创建stats对象print_stats()#Create a Stats object based on the current profile and print the results to stdout.dump_stats(filename)#Write the results of the current profile to filename.run(cmd)#Profile the cmd via exec().runctx(cmd, globals, locals)#Profile the cmd via exec() with the specified global and local environment.runcall(func, *args, **kwargs)#Profile func(*args, **kwargs)

Stats类

pstats.Stats(*filenames or profile, stream=sys.stdout)#构造函数,可以接受Profile类型的参数或者其生成文件的文件名strip_dirs()#删除报告中所有函数文件名的路径信息。如果两个项目文件名函数名行数相同,就会合并。dump_stats(filename)#生成文件sort_stats(*keys)#根据参数进行排序,多个参数就先按第一个排,相同的再按第二个排''''calls' call count'cumulative'    cumulative time'cumtime'   cumulative time'file'  file name'filename'  file name'module'    file name'ncalls'    call count'pcalls'    primitive call count'line'  line number'name'  function name'nfl'   name/file/line'stdname'   standard name'time'  internal time'tottime'   internal time'''print_stats(*restrictions)#把信息打印到stdout,里面的可选参数用于体现打印结果的形式,可以是整数、小数和字符串#整数:限制打印的行数#小数(0.0~1.0):表示按总行数的的百分比打印(一些行不打印)#字符串:正则,用于匹配stdnameprint_callers(*restrictions)#规则和上面一样,显示调用关系(右边的调用左边的)
0 0