【问题标题】:Precise time in nano seconds for Python 3.6 and earlier?Python 3.6 及更早版本的精确时间(以纳秒为单位)?
【发布时间】:2019-09-10 10:41:23
【问题描述】:

我在很多代码中都使用了这样的 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】:

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

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2021-04-06
      • 2012-10-07
      • 2015-10-09
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多