【问题标题】:Python's time.time_ns() returns same value in consecutive callsPython 的 time.time_ns() 在连续调用中返回相同的值
【发布时间】:2022-12-12 10:13:37
【问题描述】:

这个 Python 脚本

import time

while True:
    ns = time.time_ns()
    print(ns)

打印很多相同的值(虽然总是不减少)。我正在使用 Python 3.10 和 Windows 10。看起来像是时钟精度问题。有没有办法获得严格增加的价值?

【问题讨论】:

  • 所有各种选项(time.time()、time.time_ns() 等)似乎仅限于 Windows 的 ~16ms 分辨率。这里可能有一些可行的解决方案:High-precision clock in Python。

标签: python python-3.x time


【解决方案1】:

此类似乎提供更高分辨率的时间:

import time

class Timer:
    def __init__(self):
        self._offset_ns = time.time_ns() - time.perf_counter_ns()

    def time_ns(self):
        return self._offset_ns + time.perf_counter_ns()

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 2014-07-23
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多