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

标签 python python-3.x time

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

相关文章:

python - 当每个标签向文本添加样式时,处理文本小部件中的多个标签吗?

python - 以 python 方式从文件读取时一次性构建 2 个列表

python-3.x - urllib.request.urlretrieve 使用代理?

Java currentTimeMillis() 转换为秒不起作用?

postgresql - 如何在 Postgresql 中舍入时间?

python:读取json和循环字典

python - 使用列表理解从元组列表中提取第一个元素

python - 从 request.get 在 Django 中保存图像

date - x 轴上的 Gnuplot 日期/时间

python - 转换 Pandas Dataframe 类型