引言介绍
根据python编写的代码或利用python开发的框架进行二开时,有可能会遇到一些性能效率问题,这个时候我们就需要找出具体是由于那些方法或那些操作导致了效率问题。这时我们就可以利用cProfile工具进行代码监控,监控方法执行的次数和耗时。
- cProfile自python2.5以来就是标准版Python解释器默认的性能分析器。
- 其他版本的python,比如PyPy里没有cProfile的。
- cProfile是一种确定性分析器,只测量CPU时间,并不关心内存消耗和其他与内存相关联的信息。
如何使用
代码结构:
import cProfile,pstats,StringIO
pr = cProfile.Profile()
pr.enable()
# 代码块...
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
示例代码如下:
@api.multi
def _generate_purchase_order(self, requisition_lines, purchase_order_ids):
pr = cProfile.Profile()
pr.enable()
standard_num = len(requisition_lines)
if standard_num > 0:
standard_list = []
temp_list = []
standard_list.append(requisition_lines[0])
i = 1
while i < standard_num:
.....pass....
else:
return
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
显示结果
其中输出每列的具体解释如下:
- ncalls:表示函数调用的次数;
- tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;
- percall:(第一个 percall)等于 tottime/ncalls;
- cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;
- percall:(第二个 percall)即函数运行一次的平均时间,等于 cumtime/ncalls;
- filename:lineno(function):每个函数调用的具体信息;
如果需要将输出以日志的形式保存,只需要在调用的时候加入另外一个参数。如 profile.run(“profileTest()”,”testprof”)。
写在后边
当使用cProfile不能方便查看,或者信息太繁琐不喜欢的话,就用最直接的方法:打印时间
当不确定时,根据二分法和重点排除,对重点地方进行初步排查,确定大致范围之后,再对已确定的范围进行详细取样分析,也可以查到问题代码。
print ‘1001’, dateime.now()