这是关于精度的。 python 中的每个时钟都有相应的精度,这解释了您所经历的差异。让我们看看运行 MacOS Mojave 的 Macbook Pro 2018 的时钟详细信息。 Python3.7是通过brew安装的:
In [41]: time.perf_counter_ns()
Out[41]: 10464788941125
In [42]: time.process_time_ns()
Out[42]: 22502272000
In [43]: time.time_ns()
Out[43]: 1545312118561931000
In [44]: time.monotonic_ns()
Out[44]: 10477720411470
In [45]: time.get_clock_info('perf_counter')
Out[45]: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
In [46]: time.get_clock_info('process_time')
Out[46]: namespace(adjustable=False, implementation='clock_gettime(CLOCK_PROCESS_CPUTIME_ID)', monotonic=True, resolution=1.0000000000000002e-06)
In [47]: time.get_clock_info('time')
Out[47]: namespace(adjustable=True, implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, resolution=1.0000000000000002e-06)
In [48]: time.get_clock_info('monotonic')
Out[48]: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
请关注implementation
and resolution
。以下是相同的信息,但来自运行在 Ubuntu 服务器上的虚拟机:
>>> time.perf_counter_ns()
4094438601446186
>>> time.process_time_ns()
35344006
>>> time.time_ns()
1545312252720125938
>>> time.monotonic_ns()
4094449881239590
>>> time.get_clock_info('perf_counter')
namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09)
>>> time.get_clock_info('time')
namespace(adjustable=True, implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, resolution=1e-09)
>>> time.get_clock_info('process_time')
namespace(adjustable=False, implementation='clock_gettime(CLOCK_PROCESS_CPUTIME_ID)', monotonic=True, resolution=1e-09)
>>> time.get_clock_info('monotonic')
namespace(adjustable=False, implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, resolution=1e-09)
正如您所看到的,每个时钟都有不同的实现和精度,具体取决于平台。在 MacOS 上,时钟精度为process_time
and time
时钟设置为1e-06
这是微秒。这就解释了其中的差异。
您还可以使用time.clock_getres
获得精度:
In [51]: time.clock_getres(time.CLOCK_REALTIME)
Out[51]: 1.0000000000000002e-06
进一步阅读:
- https://www.webucator.com/blog/2015/08/python-clocks-explained/ https://www.webucator.com/blog/2015/08/python-clocks-explained/
- 了解clock_gettime()的不同时钟 https://stackoverflow.com/questions/7506952/understanding-the-different-clocks-of-clock-gettime