I have a function that I want to call, say, 10 times per second. I start out with code like this:
while True:
the_operation()
time.sleep(1.0/TIMES_PER_SECOND)
This works ok but the_operation is called slightly less often than desired, because the time to do the operation itself. We can make the code look like this instead:
while True:
t = time.time()
the_operation()
time_to_sleep = 1.0/TIMES_PER_SECOND - (time.time() - t)
if time_to_sleep > 0:
time.sleep(time_to_sleep)
This is better, but still not good enough -- the time to execute the loop is not considered, and if the_operation happens to take significantly longer than 1/TIMES_PER_SECOND in one iteration, our throughput will be too low. The operation on average takes less than 1/TIMES_PER_SECOND, but the code needs to handle the cases where it does take longer.
What is a good pattern for calling the_operation at the specified rate?