python - Running an action x times during t seconds uniformly -


i want repeat task several times during interval of time , want in uniform way if want task 4 times in 1 second should executed @ t = 0, 0.25, 0.5 , 0.75.

so doing:

import math import socket  s = socket.socket(...) #not important   time_step = 1./num_times_executed _ in num_times_executed:     = time.time()     s.sendto(...) #action     time.sleep(max(0,time_step-(time.time()-now))) 

however there lot of overhead, bigger loop more drift get. example num_times_executed = 800, takes 1.1 seconds ~ 10% wrong...

is there way precision ?

time_step = 1./num_times_executed start = time.time() in num_times_executed:     s.sendto(...) #action     next_send_time = start + (i+1) * time_step     time.sleep(max(0,next_send_time - time.time())) 

now you're not going drift because time steps firmly set values off of start time. little calculations happening before setting = time.time() cause tiny drift, long time_step long enough execute s.sendto(...) command, shouldn't have drift.


Comments