Python 3.6及更早版本的精确时间(纳秒)?

问题描述 投票:1回答:1

在我的很多代码中,我一直在使用这样的hack:

import time
if not hasattr(time, 'time_ns'):
    time.time_ns = lambda: int(time.time() * 1e9)

它适用于Python 3.6及更早版本的限制,它没有time_ns方法。问题是上面的解决方法是基于time.time,它返回一个浮点数。在2019年的UTC中,这大约精确到微秒级。

我如何为具有完全纳秒精度的旧版Python实现time_ns? (主要针对类UNIX系统。)

python python-3.x time
1个回答
0
投票

看看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系统。

© www.soinside.com 2019 - 2024. All rights reserved.