在 while 循环中使用 time.time() 会导致函数被调用两次

Using time.time() in while loop causes function to be called twice

我创建了一个这样的函数:

import time

def func(seconds):
    time.sleep(seconds)
    print(f'waited {seconds} seconds')

现在,如果我像这样创建一个 while loop 并调用 func(6),6 秒后,它将打印 waited 6 seconds:

start_time = time.time()
while time.time() - start_time < 5:
    func(6)

output:
waited 6 seconds

但如果我创建相同的 while loop,同时调用 func(4),脚本将等待 4 秒,然后打印 waited 4 seconds,4 秒后,它将打印 waited 4 seconds 再次!

start_time = time.time()

while time.time() - start_time < 5:
    func(4)

output:
waited 4 seconds
waited 4 seconds

为什么会这样?

我明白为什么 func(6) 会这样,但我预计 func(4) 只会执行一次,因此只打印一次 waited 4 seconds

while 条件检查是否已过五秒。对于func(6),“6 秒> 5 秒”,所以满足条件并结束while 循环。当func(4)returns时,条件“4秒>5秒”不为True,所以while循环会再循环一次。

会发生什么:

start_time = time.time()               # captures the time right now()
while time.time() - start_time < 5:    # 1.) checks the time right after last check
                                       # 3.) checks the time right after 6s passed
    func(6)                            # 2.) waits 6 seconds
                                       # 4.) done

当你使用4s时:

start_time = time.time()               # captures the time right now()
while time.time() - start_time < 5:    # 1.) checks the time right after last check
                                       # 3.) checks the time right after 4s passed, still < 5
                                       #     (should be something along 4.00023 or so)
                                       # 5.) checks the time afte4 4+4s passed
    func(4)                            # 2.) waits 4 seconds
                                       # 4.) waits 4 more seconds
                                       # 6.) done

减去时间得到一个浮点数:

import time

t = time.time()
time.sleep(1)           # guaranteed to wait at least 1s
print(time.time()-t)  

输出:

1.00106596947

time.sleep(4)之后你离5还很远——这就是它两次进入循环的原因。

针对 time-delta 计算的 while 条件 (< 5) 将允许 while 循环在 4 秒睡眠后再次进入,例如新的时间增量可能是 4.0022xxx post 前 4秒睡眠,因为条件 (4.0022xx < 5) 为真,它将导致第二次 4 秒睡眠。