这取决于时钟的类型以及您的操作系统和硬件,您是否甚至可以获得纳秒精度根本。来自time module documentation:
各种实时函数的精度可能低于其值或参数表示的单位所建议的精度。例如。在大多数 Unix 系统上,时钟每秒只“滴答”50 或 100 次。
在 Python 3 上,time 模块让您可以访问 5 种不同类型的时钟,每种都有不同的属性;其中一些可能为您提供纳秒级精度计时。使用time.get_clock_info() function 查看每个时钟提供的功能以及报告的精确时间。
在我的 OS X 10.11 笔记本电脑上,可用的功能有:
>>> for name in ('clock', 'monotonic', 'perf_counter', 'process_time', 'time'):
... print(name, time.get_clock_info(name), sep=': ')
...
clock: namespace(adjustable=False, implementation='clock()', monotonic=True, resolution=1e-06)
monotonic: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
perf_counter: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
process_time: namespace(adjustable=False, implementation='getrusage(RUSAGE_SELF)', monotonic=True, resolution=1e-06)
time: namespace(adjustable=True, implementation='gettimeofday()', monotonic=False, resolution=1e-06)
所以使用time.monotonic() 或time.perf_counter() 函数理论上会给我纳秒级的分辨率。两个时钟都没有给我墙上的时间,只有经过的时间;否则这些值是任意的。然而,它们对于测量花费了多长时间很有用。