noiftimer.noiftimer

  1from datetime import datetime
  2
  3
  4class Timer:
  5    """Simple timer class that tracks total elapsed time
  6    and average time between calls to 'start' and 'stop'."""
  7
  8    def __init__(self, averaging_window_length: int = 10):
  9        """:param averaging_window_length: Number of start/stop cycles
 10        to calculate the average elapsed time with."""
 11        self.start_time: datetime = datetime.now()
 12        self.stop_time: datetime = datetime.now()
 13        self.average_elapsed_time: float = 0
 14        self.history: list[float] = []
 15        self.elapsed_time: float = 0
 16        self.averaging_window_length: int = averaging_window_length
 17        self.started: bool = False
 18
 19    def start(self):
 20        """Start timer."""
 21        self.start_time = datetime.now()
 22        self.started = True
 23
 24    def stop(self):
 25        """Stop timer.
 26
 27        Calculates elapsed time and average elapsed time."""
 28        self.stop_time = datetime.now()
 29        self.started = False
 30        self.elapsed_time = (self.stop_time - self.start_time).total_seconds()
 31        self._save_elapsed_time()
 32        self.average_elapsed_time = sum(self.history) / (len(self.history))
 33
 34    def _save_elapsed_time(self):
 35        """Saves current elapsed time to the history buffer
 36        in a FIFO manner."""
 37        if len(self.history) >= self.averaging_window_length:
 38            self.history.pop(0)
 39        self.history.append(self.elapsed_time)
 40
 41    def current_elapsed_time(
 42        self, format: bool = True, subsecond_resolution: bool = False
 43    ) -> float | str:
 44        """Returns current elapsed without stopping the timer.
 45
 46        :param format: If True, elapsed time is returned as a string.
 47        If False, elapsed time is returned as a float."""
 48        self.elapsed_time = (datetime.now() - self.start_time).total_seconds()
 49        return (
 50            self.format_time(self.elapsed_time, subsecond_resolution)
 51            if format
 52            else self.elapsed_time
 53        )
 54
 55    def _get_time_unit(
 56        self, num_seconds: float, seconds_per_unit: float, unit_suffix: str
 57    ) -> tuple[float, str]:
 58        """Determines the number of units in a given number of seconds
 59        by integer division.
 60
 61        Returns a tuple containing the remaining number of seconds after division
 62        as well as the number of units as a string with 'unit_suffix' appended to the string.
 63
 64        e.g. _get_time_unit(124, 60, 'm') will return (4, '2m')"""
 65        num_units = int(num_seconds / seconds_per_unit)
 66        if num_units > 0:
 67            remainder = num_seconds - (num_units * seconds_per_unit)
 68            return (remainder, f"{num_units}{unit_suffix}")
 69        else:
 70            return (num_seconds, "")
 71
 72    def format_time(
 73        self, num_seconds: float, subsecond_resolution: bool = False
 74    ) -> str:
 75        """Returns num_seconds as a string with units.
 76
 77        :param subsecond_resolution: Include milliseconds
 78        and microseconds with the output."""
 79        microsecond = 0.000001
 80        millisecond = 0.001
 81        second = 1
 82        seconds_per_minute = 60
 83        seconds_per_hour = 3600
 84        seconds_per_day = 86400
 85        seconds_per_week = 604800
 86        seconds_per_month = 2419200
 87        seconds_per_year = 29030400
 88        time_units = [
 89            (seconds_per_year, "y"),
 90            (seconds_per_month, "mn"),
 91            (seconds_per_week, "w"),
 92            (seconds_per_day, "d"),
 93            (seconds_per_hour, "h"),
 94            (seconds_per_minute, "m"),
 95            (second, "s"),
 96            (millisecond, "ms"),
 97            (microsecond, "us"),
 98        ]
 99        if not subsecond_resolution:
100            time_units = time_units[:-2]
101        time_string = ""
102        for time_unit in time_units:
103            num_seconds, unit_string = self._get_time_unit(
104                num_seconds, time_unit[0], time_unit[1]
105            )
106            if unit_string != "":
107                time_string += f"{unit_string} "
108        return time_string.strip()
109
110    def get_stats(self, format: bool = True, subsecond_resolution: bool = False) -> str:
111        """Returns string for elapsed time and average elapsed time.
112
113        :param format: Times are returned as strings if True,
114        otherwise they're raw floats.
115
116        :param subsecond_resolution: Include milliseconds
117        and microseconds with the output."""
118        if format:
119            return f"elapsed time: {self.format_time(self.elapsed_time, subsecond_resolution)}\naverage elapsed time: {self.format_time(self.average_elapsed_time, subsecond_resolution)}"
120        else:
121            return f"elapsed time: {self.elapsed_time}s\naverage elapsed time: {self.average_elapsed_time}s"
class Timer:
  5class Timer:
  6    """Simple timer class that tracks total elapsed time
  7    and average time between calls to 'start' and 'stop'."""
  8
  9    def __init__(self, averaging_window_length: int = 10):
 10        """:param averaging_window_length: Number of start/stop cycles
 11        to calculate the average elapsed time with."""
 12        self.start_time: datetime = datetime.now()
 13        self.stop_time: datetime = datetime.now()
 14        self.average_elapsed_time: float = 0
 15        self.history: list[float] = []
 16        self.elapsed_time: float = 0
 17        self.averaging_window_length: int = averaging_window_length
 18        self.started: bool = False
 19
 20    def start(self):
 21        """Start timer."""
 22        self.start_time = datetime.now()
 23        self.started = True
 24
 25    def stop(self):
 26        """Stop timer.
 27
 28        Calculates elapsed time and average elapsed time."""
 29        self.stop_time = datetime.now()
 30        self.started = False
 31        self.elapsed_time = (self.stop_time - self.start_time).total_seconds()
 32        self._save_elapsed_time()
 33        self.average_elapsed_time = sum(self.history) / (len(self.history))
 34
 35    def _save_elapsed_time(self):
 36        """Saves current elapsed time to the history buffer
 37        in a FIFO manner."""
 38        if len(self.history) >= self.averaging_window_length:
 39            self.history.pop(0)
 40        self.history.append(self.elapsed_time)
 41
 42    def current_elapsed_time(
 43        self, format: bool = True, subsecond_resolution: bool = False
 44    ) -> float | str:
 45        """Returns current elapsed without stopping the timer.
 46
 47        :param format: If True, elapsed time is returned as a string.
 48        If False, elapsed time is returned as a float."""
 49        self.elapsed_time = (datetime.now() - self.start_time).total_seconds()
 50        return (
 51            self.format_time(self.elapsed_time, subsecond_resolution)
 52            if format
 53            else self.elapsed_time
 54        )
 55
 56    def _get_time_unit(
 57        self, num_seconds: float, seconds_per_unit: float, unit_suffix: str
 58    ) -> tuple[float, str]:
 59        """Determines the number of units in a given number of seconds
 60        by integer division.
 61
 62        Returns a tuple containing the remaining number of seconds after division
 63        as well as the number of units as a string with 'unit_suffix' appended to the string.
 64
 65        e.g. _get_time_unit(124, 60, 'm') will return (4, '2m')"""
 66        num_units = int(num_seconds / seconds_per_unit)
 67        if num_units > 0:
 68            remainder = num_seconds - (num_units * seconds_per_unit)
 69            return (remainder, f"{num_units}{unit_suffix}")
 70        else:
 71            return (num_seconds, "")
 72
 73    def format_time(
 74        self, num_seconds: float, subsecond_resolution: bool = False
 75    ) -> str:
 76        """Returns num_seconds as a string with units.
 77
 78        :param subsecond_resolution: Include milliseconds
 79        and microseconds with the output."""
 80        microsecond = 0.000001
 81        millisecond = 0.001
 82        second = 1
 83        seconds_per_minute = 60
 84        seconds_per_hour = 3600
 85        seconds_per_day = 86400
 86        seconds_per_week = 604800
 87        seconds_per_month = 2419200
 88        seconds_per_year = 29030400
 89        time_units = [
 90            (seconds_per_year, "y"),
 91            (seconds_per_month, "mn"),
 92            (seconds_per_week, "w"),
 93            (seconds_per_day, "d"),
 94            (seconds_per_hour, "h"),
 95            (seconds_per_minute, "m"),
 96            (second, "s"),
 97            (millisecond, "ms"),
 98            (microsecond, "us"),
 99        ]
100        if not subsecond_resolution:
101            time_units = time_units[:-2]
102        time_string = ""
103        for time_unit in time_units:
104            num_seconds, unit_string = self._get_time_unit(
105                num_seconds, time_unit[0], time_unit[1]
106            )
107            if unit_string != "":
108                time_string += f"{unit_string} "
109        return time_string.strip()
110
111    def get_stats(self, format: bool = True, subsecond_resolution: bool = False) -> str:
112        """Returns string for elapsed time and average elapsed time.
113
114        :param format: Times are returned as strings if True,
115        otherwise they're raw floats.
116
117        :param subsecond_resolution: Include milliseconds
118        and microseconds with the output."""
119        if format:
120            return f"elapsed time: {self.format_time(self.elapsed_time, subsecond_resolution)}\naverage elapsed time: {self.format_time(self.average_elapsed_time, subsecond_resolution)}"
121        else:
122            return f"elapsed time: {self.elapsed_time}s\naverage elapsed time: {self.average_elapsed_time}s"

Simple timer class that tracks total elapsed time and average time between calls to 'start' and 'stop'.

Timer(averaging_window_length: int = 10)
 9    def __init__(self, averaging_window_length: int = 10):
10        """:param averaging_window_length: Number of start/stop cycles
11        to calculate the average elapsed time with."""
12        self.start_time: datetime = datetime.now()
13        self.stop_time: datetime = datetime.now()
14        self.average_elapsed_time: float = 0
15        self.history: list[float] = []
16        self.elapsed_time: float = 0
17        self.averaging_window_length: int = averaging_window_length
18        self.started: bool = False
Parameters
  • averaging_window_length: Number of start/stop cycles to calculate the average elapsed time with.
def start(self):
20    def start(self):
21        """Start timer."""
22        self.start_time = datetime.now()
23        self.started = True

Start timer.

def stop(self):
25    def stop(self):
26        """Stop timer.
27
28        Calculates elapsed time and average elapsed time."""
29        self.stop_time = datetime.now()
30        self.started = False
31        self.elapsed_time = (self.stop_time - self.start_time).total_seconds()
32        self._save_elapsed_time()
33        self.average_elapsed_time = sum(self.history) / (len(self.history))

Stop timer.

Calculates elapsed time and average elapsed time.

def current_elapsed_time( self, format: bool = True, subsecond_resolution: bool = False) -> float | str:
42    def current_elapsed_time(
43        self, format: bool = True, subsecond_resolution: bool = False
44    ) -> float | str:
45        """Returns current elapsed without stopping the timer.
46
47        :param format: If True, elapsed time is returned as a string.
48        If False, elapsed time is returned as a float."""
49        self.elapsed_time = (datetime.now() - self.start_time).total_seconds()
50        return (
51            self.format_time(self.elapsed_time, subsecond_resolution)
52            if format
53            else self.elapsed_time
54        )

Returns current elapsed without stopping the timer.

Parameters
  • format: If True, elapsed time is returned as a string. If False, elapsed time is returned as a float.
def format_time(self, num_seconds: float, subsecond_resolution: bool = False) -> str:
 73    def format_time(
 74        self, num_seconds: float, subsecond_resolution: bool = False
 75    ) -> str:
 76        """Returns num_seconds as a string with units.
 77
 78        :param subsecond_resolution: Include milliseconds
 79        and microseconds with the output."""
 80        microsecond = 0.000001
 81        millisecond = 0.001
 82        second = 1
 83        seconds_per_minute = 60
 84        seconds_per_hour = 3600
 85        seconds_per_day = 86400
 86        seconds_per_week = 604800
 87        seconds_per_month = 2419200
 88        seconds_per_year = 29030400
 89        time_units = [
 90            (seconds_per_year, "y"),
 91            (seconds_per_month, "mn"),
 92            (seconds_per_week, "w"),
 93            (seconds_per_day, "d"),
 94            (seconds_per_hour, "h"),
 95            (seconds_per_minute, "m"),
 96            (second, "s"),
 97            (millisecond, "ms"),
 98            (microsecond, "us"),
 99        ]
100        if not subsecond_resolution:
101            time_units = time_units[:-2]
102        time_string = ""
103        for time_unit in time_units:
104            num_seconds, unit_string = self._get_time_unit(
105                num_seconds, time_unit[0], time_unit[1]
106            )
107            if unit_string != "":
108                time_string += f"{unit_string} "
109        return time_string.strip()

Returns num_seconds as a string with units.

Parameters
  • subsecond_resolution: Include milliseconds and microseconds with the output.
def get_stats(self, format: bool = True, subsecond_resolution: bool = False) -> str:
111    def get_stats(self, format: bool = True, subsecond_resolution: bool = False) -> str:
112        """Returns string for elapsed time and average elapsed time.
113
114        :param format: Times are returned as strings if True,
115        otherwise they're raw floats.
116
117        :param subsecond_resolution: Include milliseconds
118        and microseconds with the output."""
119        if format:
120            return f"elapsed time: {self.format_time(self.elapsed_time, subsecond_resolution)}\naverage elapsed time: {self.format_time(self.average_elapsed_time, subsecond_resolution)}"
121        else:
122            return f"elapsed time: {self.elapsed_time}s\naverage elapsed time: {self.average_elapsed_time}s"

Returns string for elapsed time and average elapsed time.

Parameters
  • format: Times are returned as strings if True, otherwise they're raw floats.

  • subsecond_resolution: Include milliseconds and microseconds with the output.