只需测量运行代码所需的时间即可完成循环的每个迭代,并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%完美的(可能不时关闭一毫秒或另一毫秒),但是我想这已经足够了。
另一种不错的方法是使用twisted的LoopingCall
:
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()