Skip to content

Commit

Permalink
Merge branch 'main' of github.com:miquelmassot/zeroros
Browse files Browse the repository at this point in the history
  • Loading branch information
miquelmassot committed Jan 26, 2024
2 parents 99fce25 + 710b0e9 commit ed3d3f9
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/zeroros/rate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self, frequency_hz):
@param frequency_hz: Frequency rate in Hz to determine sleeping
@type frequency_hz: float
"""
self.last_time = float(datetime.timestamp(datetime.utcnow()))
self.last_time = datetime.utcnow().timestamp()
self.sleep_dur = 1.0 / frequency_hz

def _remaining(self, curr_time):
Expand All @@ -45,16 +45,22 @@ def remaining(self):
@return: time remaining
@rtype: L{Time}
"""
curr_time = float(datetime.timestamp(datetime.utcnow()))
curr_time = datetime.utcnow().timestamp()
return self._remaining(curr_time)

def reset(self):
"""
Reset the rate timer.
"""
self.last_time = datetime.utcnow().timestamp()

def sleep(self):
"""
Attempt sleep at the specified rate. sleep() takes into
account the time elapsed since the last successful
sleep().
"""
curr_time = float(datetime.timestamp(datetime.utcnow()))
curr_time = datetime.utcnow().timestamp()
sleep(self._remaining(curr_time))
self.last_time = self.last_time + self.sleep_dur

Expand All @@ -67,13 +73,30 @@ def sleep(self):
if __name__ == "__main__":
import random

count = 0

r = Rate(10.0)
curr_time = float(datetime.timestamp(datetime.utcnow()))
while True:
diff = 1.0 / (float(datetime.timestamp(datetime.utcnow())) - curr_time)
curr_time = float(datetime.timestamp(datetime.utcnow()))
curr_time = datetime.utcnow().timestamp()
while True and count < 10:
diff = 1.0 / (datetime.utcnow().timestamp() - curr_time)
curr_time = datetime.utcnow().timestamp()
x = random.random() / 10.0
print(diff, x)
# Random time-lenght long computation
time.sleep(x)
r.sleep()
count += 1

r = Rate(1.0)
count = 0
while True:
x = random.random() / 10.0
time.sleep(x)
if r.remaining() <= 0:
diff = 1.0 / (datetime.utcnow().timestamp() - curr_time)
curr_time = datetime.utcnow().timestamp()
print(diff, x, r.remaining()) # Random time-lenght long computation
r.reset()
count += 1
if count >= 10:
break

0 comments on commit ed3d3f9

Please sign in to comment.