Reputation: 19
So I am running AirSim and I have an API that gathers data and writes it to a file. I want to limit the frequency of the write speed to 60 Hz (or write 60 times every second). How would I do this. Currently I just have the write command in a while loop.
while True:
gps_data = client.getGpsData().gnss.geo_point
alt = (gps_data.altitude)
lat = (gps_data.latitude)
lon = (gps_data.longitude)
gps_data_struct = [lat,lon,alt]
with open(output_file,'a') as gpscsvfile:
gpscsvwriter = csv.writer(gpscsvfile)
gpscsvwriter = gpscsvwriter.writerow(gps_data_struct)
#print("Altitude: %s\nLatitude %s\nLongitude %s" %(alt,lat,lon) )
if False:
break
Upvotes: 0
Views: 78
Reputation: 1747
Ok so this assumes that all the code inside the while True
takes less than 1 second to run right? If the code ends up taking longer than 1 second then the code below ends up running the code every "whole second" value after the last run. i.e. if the first run starts at 0
and takes 1.1
seconds, then the second run will start at 2
.
import time
starttime = time.time()
while True:
gps_data = client.getGpsData().gnss.geo_point
alt = gps_data.altitude
lat = gps_data.latitude
lon = gps_data.longitude
gps_data_struct = [lat, lon, alt]
with open(output_file,'a') as gpscsvfile:
gpscsvwriter = csv.writer(gpscsvfile)
gpscsvwriter = gpscsvwriter.writerow(gps_data_struct)
time.sleep(1 - ((time.time() - starttime) % 1))
If you need something more robust you could look at APScheduler
Upvotes: 0