Developing a process that should read data at consistent intervals. The time period to read data varies depending on the network. I thought this should be straightforward but I can never get consistent timing. Looking for a more consistent and stable system that responds well to network speed variability.
currently I am using a model that follows
|<--read data-->|<--post process-->|<--sleep x seconds to maintain period-->|
|<------------------------------known data rate---------------------------->|
My code does something like
data_rate = 5 # Hz
while 1:
# read in data
rd_start = time.time()
data = getdata()
rd_stop = time.time()
# Post processing
pp_start = time.time()
rate = 1.0/(rd_start - oldstart) if oldstart else data_rate
old_start = rd_start
print rate
post_process(data)
pp_stop = time.time()
sleep_time = 1.0/data_rate - ((rd_stop-rd_start) + (pp_stop-pp_start))
sleep_time = sleep_time if sleep_time>0 else 0
time.sleep(sleep_time)
I also have some logic that changes the update rate (data_rate) if the network is having trouble meeting that speed (sleep times are consistently negative) but that is working correctly.
For some reason my data rate is never consistent (And runs at about 4.92 Hz when it stabilizes). Also this method is pretty unstable. What is the better way to do this? Threading.Timers() comes to mind?
Could the consistent offset in frequency be caused by errors with time.sleep()? How accurate is python's time.sleep()?