2

I am experimenting with ways to execute blocks of code every 1 second. I have played around with APScheduler and it works really well. There is never any time drift at all. I can run it indefinitely and it will not drift.

But I am looking for a way to do it with just time.sleep().

I've read around and found that:

while True:
    start = time.time()

    function()

    time.sleep(1-(time.time() - start))

is a common solution.

However, I have been testing this for a while and I am seeing some drift.

This image shows a print datetime.now() after start = time.time():

enter image description here

As you can see, from the start of one iteration to the end takes around 1.001 seconds so after around 1000 seconds give or take, I will be off by a full second.

Does anyone have any idea on a better way for more accurate execution?

jgv115
  • 499
  • 5
  • 17
  • If you want to use the sleep method, you can implement a closed control loop for example to keep the time period somehow stable. Here is a simple type (sorry I can't reply normally): import time from datetime import datetime def do_something(): time.sleep(0.01) delta_t = 1 period = 1 current_time = time.time() next_time = current_time while True: current_time = time.time() delta_t -= (current_time - next_time)*0.9 print(delta_t) print( datetime.now()) do_something() time.sleep(delta_t) next_time = current_time + period – phev8 Aug 11 '17 at 07:27
  • I don't know why is it marked as duplicate..., the linked answer is a different one. (Sure it shows how to implement the timing, but as I see your question was to do it with the sleep method...) – phev8 Aug 11 '17 at 07:31

1 Answers1

0

Unless you know exactly how long your function takes to execute, time.sleep is a bad choice for you, first of all because the code it will be used in will assume the function between sleeps takes no time at all, and second of all because it offers no greater granularity than one second

omu_negru
  • 4,642
  • 4
  • 27
  • 38