python - Python2/3 中的 time.clock() 和 time.time() 分辨率

标签 python linux unix python-3.x

我对上述函数结果的精度感到非常非常困惑。
对我来说,文档根本不清楚,例如这里有两句话:

来自 time 模块文档

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

来自 timeit 模块文档

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.

现在因为在 Unix 中是实时的,它是由 time.time() 返回的,并且它的分辨率远远优于 1/100,它怎么可能“滴答”50 或 100 次一秒钟?


总是关于分辨率,我无法理解调用每个函数得到的确切分辨率,所以我尝试了以下方法,并将我的猜测放在评论中:

>>> time.clock()
0.038955                            # a resolution of microsecond?
>>> time.time()                     
1410633457.0955694                  # a resolution of 10-7 second?
>>> time.perf_counter()
4548.103329075                      # a resolution of 10-9 second (i.e nanosecond)?

P.S. 这是在 Python3.4.0 上尝试过的,在 Python2 中的 time.clock()time.time() 我总是得到点后有 6 个数字,所以精度为 1us?

最佳答案

精度与值变化的频率有关。

如果您可以无限快地调用这些函数中的任何一个,那么每个函数都会以不同的速率返回一个新值。

因为每个都返回一个浮点值,它没有绝对精度,所以您无法从它们的返回值中得知它们具有什么精度。您需要测量这些值如何随时间变化,以了解它们的精度是多少。

要显示差异,请运行:

import time

def average_deltas(*t):
    deltas = [t2 - t1 for t1, t2 in zip(t, t[1:])]
    return sum(deltas) / len(deltas)

for timer in time.clock, time.time, time.perf_counter:
    average = average_deltas(*(timer() for _ in range(1000))) * 10 ** 6
    print('{:<12} {:.10f}'.format(timer.__name__, average))

在我的 Mac 上打印:

clock        0.6716716717
time         0.2892525704
perf_counter 0.1550070010

因此,perf_counter 在我的架构上具有最高的精度,因为它每秒变化的频率更高,从而使值之间的增量更小。

您可以使用time.get_clock_info() function查询每种方法提供的精度:

>>> for timer in time.clock, time.time, time.perf_counter:
...     name = timer.__name__
...     print('{:<12} {:.10f}'.format(name, time.get_clock_info(name).resolution))
... 
clock        0.0000010000
time         0.0000010000
perf_counter 0.0000000010

关于python - Python2/3 中的 time.clock() 和 time.time() 分辨率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826537/

相关文章:

linux - 删除目录中的文件并打印删除的文件名

linux - 十六进制包在 Linux 上的位置

linux - TCPv4 源端口和目标端口是否可以相互冲突?还是源端口和目标端口位于它们自己的地址空间中?

python - 如何打包和分发具有需要安装驱动程序的依赖项的 Python 项目?

python - matplotlib set_major_locator 不起作用

python - Linux 下的 Selenium Chrome 驱动

linux - 从文件中的条目生成范围

vb.net - SSHAuthenticationExcetion :No suitable authentication method found to complete authentication

python - 如何从非声明性对象自动生成 SQLAlchemy 架构?

python - 执行某些步骤后无法从网页中获取动态填充的数字