Skip to main content
 首页 » 编程设计

python之time.time() 在重复调用中漂移

2025年05月04日14mate10pro

每次按这样的键我都会得到一个时间戳:

init_timestamp = time.time() 
while (True): 
    c = getch() 
    offset = time.time() - init_timestamp 
    print("%s,%s" % (c,offset), file=f) 

(getch from this answer)。

我正在根据我实际键入按键的录音来验证时间戳。在将第一个时间戳与波形对齐后,后续时间戳会轻微但始终如一地漂移。我的意思是,保存的时间戳晚于按键波形,并且随着时间的推移越来越晚。

我有理由相信波形计时是正确的(即录音不快也不慢),因为在录音中我还包括了一个非常准确的时钟的滴答声,它与第二个标记完美对齐。

我知道 time.time() 的准确性存在不可避免的限制,但这似乎并不能解释我所看到的 - 如果双方都同样错误这是可以接受的,但我不希望它逐渐偏离事实。

为什么我会看到这种漂移行为,我该怎么做才能避免这种情况?

请您参考如下方法:

刚刚通过使用 time.monotonic() 而不是 time.time() 解决了这个问题。 time.time() 似乎使用了 gettimeofday ( at least here it does ),由于 NTP 同步问题,这显然不利于测量 walltime 差异:

gettimeofday() and time() should only be used to get the current time if the current wall-clock time is actually what you want. They should never be used to measure time or schedule an event X time into the future.

You usually aren't running NTP on your wristwatch, so it probably won't jump a second or two (or 15 minutes) in a random direction because it happened to sync up against a proper clock at that point. Good NTP implementations try to not make the time jump like this. They instead make the clock go faster or slower so that it will drift to the correct time. But while it's drifting you either have a clock that's going too fast or too slow. It's not measuring the passage of time properly.

(link)。所以基本上测量 time.time() 调用之间的差异是一个坏主意。