您的位置:首页 > 编程语言 > Python开发

Python中计时,看这一篇就够了

2018-02-26 15:56 190 查看
计时对于了解程序的性能是很关键的部分。
本文讨论了Python 2和python 3中计时方法,并完成了一个通用的计时装饰器。

一、python2和python3的通用计时方法

由于python2和3里面的计时函数是不一样的,建议使用timeit模块中的timeit.default_timer()
由timeit.default_timer()的官方文档可知,计时时间精度和平台以及使用的函数有关:
"Define a default timer, in a platform-specific manner. On Windows, 
time.clock()
 has microsecond granularity, but 
time.time()
’s granularity is 1/60th of a second. On Unix, 
time.clock()
 has 1/100th of a second granularity, and 
time.time()
 is much more precise. On either platform, 
default_timer()
 measures wall clock time, not the CPU time. This means that other processes running on the same computer may interfere with the timing."
翻译过来就是,
“定义在默认的计时器中,针对不同平台采用不同方式。在Windows上,
time.clock()
具有微秒精度,但是
time.time()
精度是1/60s。在Unix上,
time.clock()
有1/100s精度,而且
time.time()
精度远远更高。在另外的平台上,
default_timer()
测量的是墙上时钟时间,不是CPU时间。这意味着同一计算机的其他进程可能影响计时。”
具体区别可以查看python2和3中timeit的实现:

python2中:if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.timepython3中:default_timer = time.perf_counter再由time.clock()的官方文档可以看出:
"Deprecated since version 3.3: The behaviour of this function depends on the platform: use 
perf_counter()
 or 
process_time()
 instead, depending on your requirements, to have a well define
abf5
d behaviour."
翻译过来就是:
“python3.3版本后time.clock()就过时了:这个函数的行为受平台影响,用
time.perf_counter()
”或者
time.process_time()
代替来得到一个定义更好的行为,具体取决于你的需求。”
更多详细信息请看官方文档中的
time.get_clock_info()

二、方便使用的计时装饰器

这一部分把计时函数写成python的装饰器形式,这样使用的时候只要在函数的定义前面加上“@装饰器名称”即可。
具体实现和测试代码如下,参考了《Fluent Python》7.7节的相关内容,并参考本文第一部分改成了Python2和Python3通用的版本。import time, timeit

def clock(func):
def clocked(*args):
t0 = timeit.default_timer()
result = func(*args)
elapsed = timeit.default_timer() - t0
name = func.__name__
arg_str = ', '.join(repr(arg) for arg in args)
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result))
return result
return clocked

@clock
def run(seconds):
time.sleep(seconds)
return time

if __name__ == '__main__':
run(1)其中的run函数只是为了测试,可以换成其他你需要的函数。只要在前面加上@clock就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 计时 装饰器