Python性能分析

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就是.001
enable()
#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):表示按总行数的的百分比打印(一些行不打印)
#字符串:正则,用于匹配stdname
print_callers(*restrictions)
#规则和上面一样,显示调用关系(右边的调用左边的)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值