How to make while loops take a set amount of time [closed]

纵然是瞬间 提交于 2019-12-08 15:34:55

问题


I'm making a digital clock in python for minecraft pi edition. I'm using a single while loop that contains a lot of code - it takes a short time to execute one run of it, but it's a few milliseconds more than I want, and this is wreaking havoc on my clock. Is there a way to make a while loop completely accurate? I'm using two counts of time.sleep(1), but it's taking longer than two seconds to execute.

Example:

while True:
    start = time.time()
    for _ in range(5):
        1000**3
    time.sleep(1)
    print (time.time() - start)

Which takes more than 1 second per loop.

1.00102806091
1.00028204918
1.00103116035
1.00051879883
1.0010240078
1.00102782249

This error accumulates over time. How can I prevent it from drifting?


回答1:


You can write time synchronization code (this sample taken from a server monitor I have):

# sync time so that it runs every two minutes, in 20 minute cycles (:00, :20, :40)
    time.sleep(1200 - (time.time() % 1200))
    while True:
        # Do stuff
        time.sleep(120 - (time.time() % 120))

If you want to run something every two seconds:

time.sleep(2 - (time.time() % 2)) 

will make it sleep until the next even second, then run. This will work unless the time to Do stuff exceeds a cycle. It will then skip a beat.

For a clock, example output:

>>> for _ in range(5): 
...     time.sleep(1 - (time.time() % 1)) 
...     print time.time()
1478641441.0
1478641442.0
1478641443.0
1478641444.0
1478641445.0

This works because time.time() % 1 gives just the fraction of a second from the current time: 0.37 for example. When I say time.sleep(1 - 0.37) it sleeps for 0.63 seconds, which is the time remaining until the next round second.

If next time it takes 0.55 seconds to run my code, it will sleep the remaining 0.45 automatically.



来源:https://stackoverflow.com/questions/40496780/how-to-make-while-loops-take-a-set-amount-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!