您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何确保Python while循环需要特定的时间才能运行?

如何确保Python while循环需要特定的时间才能运行?

只需测量运行代码所需的时间即可完成循环的每个迭代,并sleep相应地:

import time

while True:
    Now = time.time()            # get the time
    do_something()               # do your stuff
    elapsed = time.time() - Now  # how long was it running?
    time.sleep(1.-elapsed)       # sleep accordingly so the full iteration takes 1 second

当然不是100%完美的(可能不时关闭一毫秒或另一毫秒),但是我想这已经足够了。

另一种不错的方法是使用twistedLoopingCall

from twisted.internet import task
from twisted.internet import reactor

def do_something():
    pass # do your work here

task.LoopingCall(do_something).start(1.0)
reactor.run()
python 2022/1/1 18:31:36 有199人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶