try time.sleep(.01 - timer() % .01)
, to lock the sleep with the timer()
. Though it won't help if either time.sleep()
or timer()
do not support 10ms granularity. It may also depend on how Python interpreter switches between threads (GIL acquire/release) and OS scheduler (how busy the system is and how fast OS can switch between processes/threads).
To pause for a short duration, you could try a busy loop instead:
from time import monotonic as timer
deadline = timer() + .01
while timer() < deadline:
pass
For example, to do something every 10ms for a minute using time.sleep()
would probably fail:
import time
from time import monotonic as timer
now = timer()
deadline = now + 60 # a minute
while now < deadline: # do something until the deadline
time.sleep(.01 - timer() % .01) # sleep until 10ms boundary
now = timer()
print("%.06f" % (deadline - now,))
but the solution based on a busy loop should be more precise:
import time
from time import monotonic as timer
dt = .01 # 10ms
time.sleep(dt - timer() % dt)
deadline = now = timer()
outer_deadline = now + 60 # a minute
while now < outer_deadline: # do something until the deadline
print("%.06f" % (outer_deadline - now,))
# pause until the next 10ms boundary
deadline += dt
while now < deadline:
now = timer()