在n个时间后如何停止while循环?


问题内容

如果5分钟后无法达到我想要的效果,我如何停止while循环。

while true:
    test = 0
    if test == 5:
        break
    test = test - 1

这段代码使我陷入无限循环。


问题答案:

请尝试以下操作:

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    test = test - 1

您可能还想在此处添加短暂睡眠,以使此循环不会占用CPU(例如time.sleep(1),在循环主体的开头或结尾)。