Apr-19-2021, 05:55 PM
Hi
I am trying to get my while loop to run at a specific frequency (30Hz) and am having trouble getting it to work. I'm going with 30Hz x 60 seconds should give me a max run of 1800 loops. I am also checking start/end times and taking differences to determine a pause time.
Typical output from my script (I'd like to figure out if this can get close to the 1800 mark):
Thanks...
I am trying to get my while loop to run at a specific frequency (30Hz) and am having trouble getting it to work. I'm going with 30Hz x 60 seconds should give me a max run of 1800 loops. I am also checking start/end times and taking differences to determine a pause time.
Typical output from my script (I'd like to figure out if this can get close to the 1800 mark):
Output:Number of loops: 1251
Not paused: 0
Time delta is : 60.01318955421448
This is my test code:#!/usr/bin/env python import time import pause frequency = 30 # Hz period = (1.0/frequency)*1000 timeToRun = 1 # how many minutes to run t_end = time.time() + 60 * timeToRun # run for timeToRun minutes notPaused = 0 numRuns = 0 elapsedDiffList = [] startTime = time.time() while time.time() <= t_end: timeNowMilli = time.time_ns()/1000000 # time from nanoseconds to milliseconds timeEndMilli = time.time_ns()/1000000 pause.milliseconds(1) elapsedDiff = timeEndMilli - timeNowMilli if elapsedDiff < period: # done before our schedule -- pause awhile timeToPause = period-elapsedDiff pause.milliseconds(timeToPause) else: # took longer than scheduled -- send next message right away without pause elapsedDiffList.append(elapsedDiff) # incase I get an extra long loop notPaused += 1 numRuns += 1 endTime = time.time() time_delta = (endTime-startTime) print() print("Number of loops: " + str(numRuns)) print("Not paused: ", str(notPaused)) print('Time delta is : ' + str(time_delta)) print(*elapsedDiffList, sep=", ")It doesn't feel like I'm getting a 30Hz loop out of this. Any idea what I'm missing?
Thanks...