天天看点

[zz]Python:time.clock() vs. time.time()

http://mrwlwan.wordpress.com/2008/09/19/python%EF%BC%9Atimeclock-vs-timetime/

Python:time.clock() vs. time.time()

作者 Ross Wan on 2008/09/19

有时候,我们需要知道程序或者当中的一段代码的执行速度,于是就会加入一段计时的代码,如下:

start = time.clock()
    ... do something
elapsed = (time.clock() - start)      

又或者

start = time.time()
    ... do something
elapsed = (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.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time      

使用 timeit 代替 time,这样就可以实现跨平台的精度性:

start = timeit.default_timer()
    ... do something
elapsed = (timeit.default_timer() - start)      

参考资料:

  • http://coreygoldberg.blogspot.com/2008/09/python-timing-timeclock-vs-timetime.html
  • http://docs.python.org/lib/module-time.html