Skip to main content
 首页 » 编程设计

python之在 Python 上使用 time.time() 完美计时

2025年05月04日12zengkefu

time.time() :

Return the time in seconds since the epoch as a floating point number. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

想问一下time.time()在Raspberry Pi上的作用。我正在编写一个代码,我必须在其中组织一个具有完美时间的系统 [例如,每 5 秒做一次,而不是多一秒!永远!]。但是,我注意到当 time.time() 的十进制值介于 .95-.05 之间时,秒数增加,而不是在十进制值为 .00 时增加

例子:如果时间是1439286302.64,那么按照十进制,到达~1439286302.9x时会增加1秒。有谁知道它将增加 1 秒的确切边界是什么?因为我一直在测试,这似乎是随机的,我在网上找不到答案。

感谢所有帮助。

请您参考如下方法:

一些伪代码应该至少让你保持平均每 5 秒一次,而不是复合抖动

time_started = time.time() 
next_action_time = int(time_started) + 5 
while True: 
    if next_action_time < time.time(): 
        do_action!!!!! 
        next_action_time += 5 
    else: 
        waste_some_time() 

确保您的其他流程符合您的时间预算。也可以让你的 so_actions 采样记录测量完成的实际时间。通过这种方式,您可以确认抖动已得到控制。