python的time模块没有clock_Python:time.clock() vs. time.time()

有时候,我们需要知道程序或者当中的一段代码的执行速度,于是就会加入一段计时的代码,如下:start = time.clock() ... do somethingelapsed = (time.clock() - start)

又或者start = time.time() ... do somethingelapsed = (time.time() - start)

那究竟 time.clock() 跟 time.time(),谁比较精确呢?带着疑问,查了 Python 的 time 模块文档,当中 clock() 方法有这样的解释:

clock()

On

Unix, return the current processor time as a floating point number

expressed in seconds. The precision, and in fact the very definition of

the meaning of “processor time”, depends on that of the C function of

the same name, but in any case, this is the function to use for

benchmarking Python or timing algorithms.

On Windows, this

function returns wall-clock seconds elapsed since the first call to

this function, as a floating point number, based on the Win32 function

QueryPerformanceCounter(). The resolution is typically better than one

microsecond.

可见,time.clock() 返回的是处理器时间,而因为 Unix 中 jiffy 的缘故,所以精度不会太高。

总结

究竟是使用 time.clock() 精度高,还是使用 time.time() 精度更高,要视乎所在的平台来决定。总概来讲,在 Unix 系统中,建议使用 time.time(),在 Windows 系统中,建议使用 time.clock()。

这个结论也可以在 Python 的 timtit 模块中(用于简单测量程序代码执行时间的内建模块)得到论证:if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clockelse: # On most other platforms the best timer is time.time() default_timer = time.time

使用 timeit 代替 time,这样就可以实现跨平台的精度性:start = timeit.default_timer() ... do somethingelapsed = (timeit.default_timer() - start)

参考资料:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值