关键在于精准。python中的每个时钟都有相应的精度,这可以解释您所经历的差异。让我们看看MacBook Pro 2018和MacOS Mojave的时钟细节。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
和
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
和
time
时钟设置为
1e-06
也就是微秒。这就解释了区别。
您也可以使用
time.clock_getres
要获得精度:
In [51]: time.clock_getres(time.CLOCK_REALTIME)
Out[51]: 1.0000000000000002e-06
进一步阅读: