一、Python cprofile 简介
Python 自带的 cprofile 库,可以对代码的每部分进行很方便的动态分析;
比如准确计算出每个模块消耗的时间等。这样你就可以知道程序的瓶颈所在,从而方便针对性地对其进行修正或优化。
二、Python cprofile 使用方法
1、import 使用
#!/usr/bin/python2.7
# test.py
import time
import cProfile
import pdb
pdb.set_trace()
def testcal(a, b, c):
e = (a + b) * c
print "(a + b) * c =", e
e = ((a + b) * c)
print "((a + b) * c) =", e
time.sleep(5) # 测试执行耗时
e = a + (b * c)
print "a + (b * c) =", e
if __name__=='__main__':
a = 20
b = 10
c = 15
cProfile.run('testcal(a, b, c)')
2、命令行直接用
python -m cProfile test.py
三、Python cprofile 输出简析
运行结果如下所示:
/tmp/test.py(9)<module>()
-> a = 20
(Pdb) c
(a + b) * c = 450
((a + b) * c)