I am trying to create a larger Python script that procures data from external sources and then logs them into a csv file. I have isolated the code I have written for this purpose and it is as follows:
loop_time = time.time()
wait_time = 1
try:
while True:
idle_time = (math.ceil((time.time() - loop_time)*1000))
loop_time= time.time()
rand1 = math.ceil(random.uniform(0,3))
rand2 = math.ceil(random.uniform(0,60))
wait_time_ms = math.ceil(wait_time*1000)
csvlogger.lvl1([rand1,rand2,idle_time, wait_time_ms])
execution_time = time.time()-loop_time
wait_time = 1 - execution_time
sleep(wait_time)
except KeyboardInterrupt:
print("end of log generation")
My problem is that I need the data logging to occur as close as possible to 1000ms, and one of the data fields in the generated file must include the "idle time", i.e. how long the execution of the loop took place.
When I run the code above I get the following output:
time,Current Output,Voltage Output,Idle Time,Wait Time
15:13:03.314,3,48,0,1000
15:13:04.322,3,59,1009,1000
15:13:05.331,1,36,1009,1000
15:13:06.346,2,8,1015,1000
As you can see, the resulting time is a few miliseconds too large. I do realise it is perhaps nitpicky for most applications, but it is quite important for my purposes. Additionally, I will ultimately have many more things happening in the loop, some of which might actually lead to the execution time larger than 1000ms on certain occasions, so I would appreciate any suggestions for a loop time control that could also account for that.