You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python time.time_ns()连续调用返回相同值,如何获取严格递增结果?

获取严格递增的纳秒级数值(Windows 10 + Python 3.10)

你遇到的问题确实是Windows系统时钟精度限制导致的——time.time_ns()底层依赖的系统计时器精度通常在10~16毫秒左右,快速循环调用时会重复返回同一值。以下两种方法可以解决这个问题:

方法1:使用系统高精度硬件计时器

Windows提供了QueryPerformanceCounter和QueryPerformanceFrequency接口,能获取微秒级甚至更高精度的计时,需要先安装pywin32库(执行pip install pywin32):

import win32api

# 获取计时器频率(每秒计数次数)
freq = win32api.QueryPerformanceFrequency()
# 记录初始计数
start_count = win32api.QueryPerformanceCounter()

while True:
    current_count = win32api.QueryPerformanceCounter()
    # 转换为纳秒数
    ns = (current_count - start_count) * 10**9 // freq
    print(ns)

这种方法基于硬件计时器,精度极高,能保证数值严格递增,适合需要真实高精度时间戳的场景。

方法2:软件层面维护递增序列

如果不需要真实的时间戳,只是需要一个严格递增的数值序列,可以自己维护一个计数器,结合time.time_ns()确保每次返回值都比前一次大:

import time

last_value = 0
while True:
    current_value = time.time_ns()
    # 如果当前值不大于上一次,就强制加1
    if current_value <= last_value:
        current_value = last_value + 1
    last_value = current_value
    print(last_value)

这种方法不需要额外依赖,逻辑简单,但数值可能不是真实的系统时间,适合只需要递增标识的场景。

内容的提问来源于stack exchange,提问作者user3749105

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:15:34