前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python中计时,看这一篇就够了

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

作者头像
py3study
发布2020-01-06 16:13:56
3K0
发布2020-01-06 16:13:56
举报
文章被收录于专栏:python3python3python3

计时对于了解程序的性能是很关键的部分。

本文讨论了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.time python3中:

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 defined 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就可以了。 ---------------------  作者:FlyingPie  来源:CSDN  原文:https://blog.csdn.net/bobauditore/article/details/79377679?utm_source=copy  版权声明:本文为博主原创文章,转载请附上博文链接!

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档