我需要在精确的时间段内运行一个循环。例如,我尝试编写的代码应该如下所示:
initialize and lauch timer
while timer<10000sec:
do things
你知道如何做到这一点吗?
谢谢 :)
stop = time.time()+10000
while time.time() < stop:
do things
这要求每次循环都足够短,以便您足够频繁地读取当前时间(为了达到您想要的精度)。
time.time()
可能会占据运行时间的主导地位。我的意思是,如果性能在这里非常关键,他可以考虑另一种方法。 - Eli Benderskyimport time
t_end = time.time() + 60 * <> #duration goes inside <>; eg 2 for 2 minutes
while time.time() < t_end:
#rest of the code
do things
应该被中止还是应该先完成? - plundra