From ca1e1938c417c79fa712ef1d2e2b910f5c85d0fa Mon Sep 17 00:00:00 2001 From: Kenny Date: Mon, 15 Nov 2021 22:32:23 -0800 Subject: [PATCH] integer math Durations If you specify your interval as asynccp.time.Duration.of_nanoseconds() there will be no unit conversion math done on the interval provided by your code. Also reduces the quantity of floating point math in other places to avoid cascading inaccuracies more than necessary. --- asynccp/loop.py | 4 ++-- asynccp/time.py | 28 ++++++++++++++-------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/asynccp/loop.py b/asynccp/loop.py index 173656a..e2f347a 100755 --- a/asynccp/loop.py +++ b/asynccp/loop.py @@ -59,10 +59,10 @@ class ScheduledTask: def change_rate(self, frequency): """ Update the task rate to a new frequency. Float hz or asynccp.time.Duration interval """ if isinstance(frequency, asynccp.time.Duration): - hz = frequency.as_frequency() + self._nanoseconds_per_invocation = frequency.as_nanoseconds() else: hz = frequency - self._nanoseconds_per_invocation = (1 / hz) * 1000000000 + self._nanoseconds_per_invocation = 1000000000 / hz def stop(self): """ Stop the task (does not interrupt a currently running task) """ diff --git a/asynccp/time.py b/asynccp/time.py index 3a2109f..68d79f2 100644 --- a/asynccp/time.py +++ b/asynccp/time.py @@ -2,48 +2,48 @@ class Duration: @staticmethod def of_hours(count): - return Duration(count * 60 * 60 * 1000000) + return Duration(count * 60 * 60 * 1000000000) @staticmethod def of_minutes(count): - return Duration(count * 60 * 1000000) + return Duration(count * 60 * 1000000000) @staticmethod def of_seconds(count): - return Duration(count * 1000000) + return Duration(count * 1000000000) @staticmethod def of_milliseconds(count): - return Duration(count * 1000) + return Duration(count * 1000000) @staticmethod def of_microseconds(count): return Duration(count) - def __init__(self, microseconds): - self._microseconds = int(microseconds) + def __init__(self, nanoseconds): + self._nanoseconds = int(nanoseconds) def __add__(self, other): - return Duration(self._microseconds + other._microseconds) + return Duration(self._nanoseconds + other._nanoseconds) def __sub__(self, other): - return Duration(self._microseconds - other._microseconds) + return Duration(self._nanoseconds - other._nanoseconds) def __neg__(self): - return Duration(-1 * self._microseconds) + return Duration(-1 * self._nanoseconds) def as_frequency(self): """returns this duration as a frequency interval in HZ""" - return 1000000.0 / self._microseconds + return 1000000000.0 / self._nanoseconds def as_seconds(self): - return self._microseconds / 1000000.0 + return self._nanoseconds / 1000000000.0 def as_milliseconds(self): - return self._microseconds / 1000.0 + return self._nanoseconds / 1000000.0 def as_microseconds(self): - return self._microseconds + return self._nanoseconds / 1000.0 def as_nanoseconds(self): - return self._microseconds * 1000 + return self._nanoseconds