我在很多代码中都使用了这样的 hack:
import time
if not hasattr(time, 'time_ns'):
time.time_ns = lambda: int(time.time() * 1e9)
它解决了 Python 3.6 及更早版本的限制,该版本没有 time_ns
方法。问题是上述解决方法基于 time.time
,它返回一个 float 。在 2019 年的 UTC 中,这大约精确到微秒尺度。
如何为旧版本的 Python 实现 time_ns
并具有完全纳秒精度? (主要针对类 UNIX 系统。)
最佳答案
查看CPython source code ,可推导出如下:
import ctypes
CLOCK_REALTIME = 0
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_int64), # seconds, https://stackoverflow.com/q/471248/1672565
('tv_nsec', ctypes.c_int64), # nanoseconds
]
clock_gettime = ctypes.cdll.LoadLibrary('libc.so.6').clock_gettime
clock_gettime.argtypes = [ctypes.c_int64, ctypes.POINTER(timespec)]
clock_gettime.restype = ctypes.c_int64
def time_ns():
tmp = timespec()
ret = clock_gettime(CLOCK_REALTIME, ctypes.pointer(tmp))
if bool(ret):
raise OSError()
return tmp.tv_sec * 10 ** 9 + tmp.tv_nsec
上面的代码适用于 64 位类 UNIX 系统。
关于python - Python 3.6 及更早版本的精确时间(纳秒)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55774054/