昨天学到一招,不用像之前一样想看程序执行慢的时候到底慢在哪里就到处写"start_time = time.time() end_time = time.time() use_time = end_time - start_time"了,有一个profile模块可以查看执行过程中各个调用的耗时。
用法是:
import profile
……
profile.run('exe_str')
这里的exe_str代表的就是把我们要执行的代码以字符串形式给profile,如果代码里有单引号要么转义掉,要么字符串外面换用双引号。
比如:
# -*- coding:utf-8 -*-
import profile
import time
def tell_time():
for i in range(10):
print time.time()
profile.run('tell_time()')
然后除了你代码里输出的东西以外还会有一堆这种东西
15 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(range)
1 0.001 0.001 0.001 0.001 :0(setprofile)
10 0.000 0.000 0.000 0.000 :0(time)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.001 0.001 profile:0(tell_time())
1 0.000 0.000 0.000 0.000 say_hello_profile.py:5(tell_time)
这就是profile返回的程序各个部分的性能情况,很容易找到程序的性能瓶颈。
结果里各项的意义:
ncalls | 函数的被调用次数 |
tottime | 函数总计运行时间,除去函数中调用的函数运行时间 |
percall | 函数运行一次的平均时间,等于tottime/ncalls |
cumtime | 函数总计运行时间,含调用的函数运行时间 |
percall | 函数运行一次的平均时间,等于cumtime/ncalls |