Python内置监控模块cProfile可以监控程序内耗,对性能分析很有帮助。相关的还有profile、pstats、timeit和hotshot,cProfile可以检测到中断并保存数据。如下test.py:
times = 1000000def foo():
sum = 0
for i in range(10):
sum += 1
sum = 0
def useFoo():
foo()
def app1():
global times
for i in range(times):
foo()
def app2():
global times
for i in range(times):
useFoo()
app1()
app2()
执行:python -m cProfile -s time test.py 结果如下:
5000008 function calls in 26.522 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
2000000 11.705 0.000 16.949 0.000 test.py:2(foo)
2000002 5.306 0.000 5.306 0.000 {range}
1000000 4.796 0.000 14.812 0.000 test.py:8(useFoo)
1 2.732 2.732 17.566 17.566 test.py:17(app2)
1 1.982 1.982 8.954 8.954 test.py:12(app1)
1 0.001 0.001 26.522 26.522 {execfile}
1 0.000 0.000 26.520 26.520 test.py:1(<module>)
1 0.000 0.000 26.522 26.522 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
.
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
示例代码执行了两个函数,其中一个只是调用另一个。结果除了反应出程序各模块的耗时之外,也反应出Python函数调用的耗时:本示例中函数调用耗时多了一倍。
另外有一个带GUI的工具VisualPyTune (vpt) ,支持profile、cProfile、hotspot和timeit,小试了一下截个图: