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()
:
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?