Why Profile
即使我们的代码已经非常Pythonic了,但运行效率还是不能满足要求。性能问题符合20/80规则,即20%的代码引起了80%的性能损耗。为了快速定位瓶颈代码,推荐通过Profile来分析,能到达事半功倍的效果。
Python Profile
对于Python,比较常用的Profile工具有三个:
profile 纯python语言实现,返回函数整体损耗。(自带)[详情]
cProfile 同profile,部分实现native化,返回函数整体损耗。(自带)
line_profile 返回函数每行损耗。(第三方)[详情]
Profile Usage
profile
# 这里使用vsm模型进行测试
from profile import Profile
p = Profile()
p.runcall(vsm, tags[0], tags[1])
p.print_stats()
# ncalls 函数总的调用次数
# tottime 函数内部(不包括子函数)的占用时间
# percall(第一个) tottime/ncalls
# cumtime 函数包括子函数所占用的时间
# percall(第二个)cumtime/ncalls
# filename:lineno(function) 文件:行号(函数)
212 function calls in 0.002 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(funct