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

 

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

本文讨论了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, **kwargs):
        t0 = timeit.default_timer()
        result = func(*args, **kwargs)
        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就可以了。

 

 

  • 12
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值