Reputation: 3221
On python 3 I need to stop until a certain time. And I need to be fairly precise on when I wake up. The problem is that in this pause I should do some calculations that will take part of that time. So I cannot just time.sleep()
through it or I would start too late.
So I was thinking of running this code:
import time
wakeuptime=time.time()+20 #start again exactly 20 seconds from now
UnpredictablySlowFunction()
while (time.time()<wakeuptime):
pass
I am a bit worried that this kind of loop might be more uselessly CPU-intensive than a normal time.sleep()
. Especially considering the program should run in the background 24/7.
Upvotes: 2
Views: 475
Reputation: 5709
As @tobias_k mentioned in comment, try this:
import time
wakeuptime=time.time()+20 #start again exactly 20 seconds from now
UnpredictablySlowFunction()
time_left = wakeuptime -time.time()
time.sleep(time_left)
Upvotes: 7