Monday, April 29, 2013

Python precision timing a loop with sleep

Here is my lovely timed loop, making use of suggestions that I'd already picked up earlier from several places. Since there's stuff in the loop that has an indeterminate run time, in order to make the loop start at the same interval of elapsed time every time, the secret is to count in increments of elapsed time from a start time taken before the first loop, and use while and sleep to wait until the next time interval threshold is crossed to do the next iteration (rather than just doing a single hard-coded wait, which will result in drift):


import datetime as dt

starttime = dt.datetime.now()
loopcount = 0
period = x #seconds

while([loop condition]):
[stuff that the loop does]
loopcount = loopcount + 1
nexttime = starttime + dt.timedelta(seconds=(period*loopcount))
timenow = dt.datetime.now()
while (nexttime > timenow):
time.sleep(0.1)
timenow = dt.datetime.now()

Here's a nice link that I found this time that shows how to do adding seconds to a time in python:
http://stackoverflow.com/questions/100210/python-easy-way-to-add-n-seconds-to-a-datetime-time