noiftimer.noiftimer

  1import time
  2from typing import Any, Callable
  3
  4from typing_extensions import Self
  5
  6
  7def time_it(loops: int = 1) -> Callable[..., Any]:
  8    """Decorator to time function execution time
  9    and print the results.
 10
 11    :param loops: How many times to loop the function,
 12    starting and stopping the timer before and after
 13    each loop."""
 14
 15    def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
 16        def wrapper(*args, **kwargs) -> Any:
 17            timer = Timer(loops)
 18            result = None
 19            for _ in range(loops):
 20                timer.start()
 21                result = func(*args, **kwargs)
 22                timer.stop()
 23            print(
 24                f"{func.__name__} average execution time: {timer.average_elapsed_str}"
 25            )
 26            return result
 27
 28        return wrapper
 29
 30    return decorator
 31
 32
 33class Timer:
 34    """Simple timer class that tracks total elapsed time
 35    and average time between calls to 'start' and 'stop'."""
 36
 37    def __init__(
 38        self, averaging_window_length: int = 10, subsecond_resolution: bool = True
 39    ):
 40        """:param averaging_window_length: Number of start/stop cycles
 41        to calculate the average elapsed time with.
 42
 43        :param subsecond_resolution: Whether to print formatted time
 44        strings with subsecond resolution or not."""
 45        self._start_time = time.time()
 46        self._stop_time = self.start_time
 47        self._elapsed = 0
 48        self._average_elapsed = 0
 49        self._history: list[float] = []
 50        self._started: bool = False
 51        self.averaging_window_length: int = averaging_window_length
 52        self.subsecond_resolution = subsecond_resolution
 53
 54    @property
 55    def started(self) -> bool:
 56        """Returns whether the timer has
 57        been started and is currently running."""
 58        return self._started
 59
 60    @property
 61    def elapsed(self) -> float:
 62        """Return the currently elapsed time."""
 63        if self._started:
 64            return time.time() - self._start_time
 65        else:
 66            return self._elapsed
 67
 68    @property
 69    def elapsed_str(self) -> str:
 70        """Return the currently elapsed time
 71        as a formatted string."""
 72        return self.format_time(self.elapsed, self.subsecond_resolution)
 73
 74    @property
 75    def average_elapsed(self) -> float:
 76        return self._average_elapsed
 77
 78    @property
 79    def average_elapsed_str(self) -> str:
 80        return self.format_time(self._average_elapsed, self.subsecond_resolution)
 81
 82    @property
 83    def start_time(self) -> float:
 84        return self._start_time
 85
 86    @property
 87    def stop_time(self) -> float:
 88        return self._stop_time
 89
 90    @property
 91    def history(self) -> list[float]:
 92        return self._history
 93
 94    def start(self: Self) -> Self:
 95        """Start timer.
 96        Returns this Timer instance so
 97        timer start can be chained to
 98        Timer creation.
 99
100        >>> timer = Timer().start()"""
101        self._start_time = time.time()
102        self._started = True
103        return self
104
105    def stop(self):
106        """Stop timer.
107
108        Calculates elapsed time and average elapsed time."""
109        self._stop_time = time.time()
110        self._started = False
111        self._elapsed = self._stop_time - self._start_time
112        self._save_elapsed_time()
113        self._average_elapsed = sum(self._history) / (len(self._history))
114
115    def _save_elapsed_time(self):
116        """Saves current elapsed time to the history buffer
117        in a FIFO manner."""
118        if len(self._history) >= self.averaging_window_length:
119            self._history.pop(0)
120        self._history.append(self._elapsed)
121
122    @staticmethod
123    def format_time(num_seconds: float, subsecond_resolution: bool = False) -> str:
124        """Returns num_seconds as a string with units.
125
126        :param subsecond_resolution: Include milliseconds
127        and microseconds with the output."""
128        microsecond = 0.000001
129        millisecond = 0.001
130        second = 1
131        seconds_per_minute = 60
132        seconds_per_hour = 3600
133        seconds_per_day = 86400
134        seconds_per_week = 604800
135        seconds_per_month = 2419200
136        seconds_per_year = 29030400
137        time_units = [
138            (seconds_per_year, "y"),
139            (seconds_per_month, "mn"),
140            (seconds_per_week, "w"),
141            (seconds_per_day, "d"),
142            (seconds_per_hour, "h"),
143            (seconds_per_minute, "m"),
144            (second, "s"),
145            (millisecond, "ms"),
146            (microsecond, "us"),
147        ]
148        if not subsecond_resolution:
149            time_units = time_units[:-2]
150        time_string = ""
151        for time_unit in time_units:
152            unit_amount, num_seconds = divmod(num_seconds, time_unit[0])
153            if unit_amount > 0:
154                time_string += f"{int(unit_amount)}{time_unit[1]} "
155        if time_string == "":
156            return f"<1{time_units[-1][1]}"
157        return time_string.strip()
158
159    @property
160    def stats(self) -> str:
161        """Returns a string stating the currently elapsed time
162        and the average elapsed time."""
163        return f"elapsed time: {self.elapsed_str}\naverage elapsed time: {self.average_elapsed_str}"
def time_it(loops: int = 1) -> Callable[..., Any]:
 8def time_it(loops: int = 1) -> Callable[..., Any]:
 9    """Decorator to time function execution time
10    and print the results.
11
12    :param loops: How many times to loop the function,
13    starting and stopping the timer before and after
14    each loop."""
15
16    def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
17        def wrapper(*args, **kwargs) -> Any:
18            timer = Timer(loops)
19            result = None
20            for _ in range(loops):
21                timer.start()
22                result = func(*args, **kwargs)
23                timer.stop()
24            print(
25                f"{func.__name__} average execution time: {timer.average_elapsed_str}"
26            )
27            return result
28
29        return wrapper
30
31    return decorator

Decorator to time function execution time and print the results.

Parameters
  • loops: How many times to loop the function, starting and stopping the timer before and after each loop.
class Timer:
 34class Timer:
 35    """Simple timer class that tracks total elapsed time
 36    and average time between calls to 'start' and 'stop'."""
 37
 38    def __init__(
 39        self, averaging_window_length: int = 10, subsecond_resolution: bool = True
 40    ):
 41        """:param averaging_window_length: Number of start/stop cycles
 42        to calculate the average elapsed time with.
 43
 44        :param subsecond_resolution: Whether to print formatted time
 45        strings with subsecond resolution or not."""
 46        self._start_time = time.time()
 47        self._stop_time = self.start_time
 48        self._elapsed = 0
 49        self._average_elapsed = 0
 50        self._history: list[float] = []
 51        self._started: bool = False
 52        self.averaging_window_length: int = averaging_window_length
 53        self.subsecond_resolution = subsecond_resolution
 54
 55    @property
 56    def started(self) -> bool:
 57        """Returns whether the timer has
 58        been started and is currently running."""
 59        return self._started
 60
 61    @property
 62    def elapsed(self) -> float:
 63        """Return the currently elapsed time."""
 64        if self._started:
 65            return time.time() - self._start_time
 66        else:
 67            return self._elapsed
 68
 69    @property
 70    def elapsed_str(self) -> str:
 71        """Return the currently elapsed time
 72        as a formatted string."""
 73        return self.format_time(self.elapsed, self.subsecond_resolution)
 74
 75    @property
 76    def average_elapsed(self) -> float:
 77        return self._average_elapsed
 78
 79    @property
 80    def average_elapsed_str(self) -> str:
 81        return self.format_time(self._average_elapsed, self.subsecond_resolution)
 82
 83    @property
 84    def start_time(self) -> float:
 85        return self._start_time
 86
 87    @property
 88    def stop_time(self) -> float:
 89        return self._stop_time
 90
 91    @property
 92    def history(self) -> list[float]:
 93        return self._history
 94
 95    def start(self: Self) -> Self:
 96        """Start timer.
 97        Returns this Timer instance so
 98        timer start can be chained to
 99        Timer creation.
100
101        >>> timer = Timer().start()"""
102        self._start_time = time.time()
103        self._started = True
104        return self
105
106    def stop(self):
107        """Stop timer.
108
109        Calculates elapsed time and average elapsed time."""
110        self._stop_time = time.time()
111        self._started = False
112        self._elapsed = self._stop_time - self._start_time
113        self._save_elapsed_time()
114        self._average_elapsed = sum(self._history) / (len(self._history))
115
116    def _save_elapsed_time(self):
117        """Saves current elapsed time to the history buffer
118        in a FIFO manner."""
119        if len(self._history) >= self.averaging_window_length:
120            self._history.pop(0)
121        self._history.append(self._elapsed)
122
123    @staticmethod
124    def format_time(num_seconds: float, subsecond_resolution: bool = False) -> str:
125        """Returns num_seconds as a string with units.
126
127        :param subsecond_resolution: Include milliseconds
128        and microseconds with the output."""
129        microsecond = 0.000001
130        millisecond = 0.001
131        second = 1
132        seconds_per_minute = 60
133        seconds_per_hour = 3600
134        seconds_per_day = 86400
135        seconds_per_week = 604800
136        seconds_per_month = 2419200
137        seconds_per_year = 29030400
138        time_units = [
139            (seconds_per_year, "y"),
140            (seconds_per_month, "mn"),
141            (seconds_per_week, "w"),
142            (seconds_per_day, "d"),
143            (seconds_per_hour, "h"),
144            (seconds_per_minute, "m"),
145            (second, "s"),
146            (millisecond, "ms"),
147            (microsecond, "us"),
148        ]
149        if not subsecond_resolution:
150            time_units = time_units[:-2]
151        time_string = ""
152        for time_unit in time_units:
153            unit_amount, num_seconds = divmod(num_seconds, time_unit[0])
154            if unit_amount > 0:
155                time_string += f"{int(unit_amount)}{time_unit[1]} "
156        if time_string == "":
157            return f"<1{time_units[-1][1]}"
158        return time_string.strip()
159
160    @property
161    def stats(self) -> str:
162        """Returns a string stating the currently elapsed time
163        and the average elapsed time."""
164        return f"elapsed time: {self.elapsed_str}\naverage elapsed time: {self.average_elapsed_str}"

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

Timer(averaging_window_length: int = 10, subsecond_resolution: bool = True)
38    def __init__(
39        self, averaging_window_length: int = 10, subsecond_resolution: bool = True
40    ):
41        """:param averaging_window_length: Number of start/stop cycles
42        to calculate the average elapsed time with.
43
44        :param subsecond_resolution: Whether to print formatted time
45        strings with subsecond resolution or not."""
46        self._start_time = time.time()
47        self._stop_time = self.start_time
48        self._elapsed = 0
49        self._average_elapsed = 0
50        self._history: list[float] = []
51        self._started: bool = False
52        self.averaging_window_length: int = averaging_window_length
53        self.subsecond_resolution = subsecond_resolution
Parameters
  • averaging_window_length: Number of start/stop cycles to calculate the average elapsed time with.

  • subsecond_resolution: Whether to print formatted time strings with subsecond resolution or not.

started: bool

Returns whether the timer has been started and is currently running.

elapsed: float

Return the currently elapsed time.

elapsed_str: str

Return the currently elapsed time as a formatted string.

def start(self: Self) -> Self:
 95    def start(self: Self) -> Self:
 96        """Start timer.
 97        Returns this Timer instance so
 98        timer start can be chained to
 99        Timer creation.
100
101        >>> timer = Timer().start()"""
102        self._start_time = time.time()
103        self._started = True
104        return self

Start timer. Returns this Timer instance so timer start can be chained to Timer creation.

>>> timer = Timer().start()
def stop(self):
106    def stop(self):
107        """Stop timer.
108
109        Calculates elapsed time and average elapsed time."""
110        self._stop_time = time.time()
111        self._started = False
112        self._elapsed = self._stop_time - self._start_time
113        self._save_elapsed_time()
114        self._average_elapsed = sum(self._history) / (len(self._history))

Stop timer.

Calculates elapsed time and average elapsed time.

@staticmethod
def format_time(num_seconds: float, subsecond_resolution: bool = False) -> str:
123    @staticmethod
124    def format_time(num_seconds: float, subsecond_resolution: bool = False) -> str:
125        """Returns num_seconds as a string with units.
126
127        :param subsecond_resolution: Include milliseconds
128        and microseconds with the output."""
129        microsecond = 0.000001
130        millisecond = 0.001
131        second = 1
132        seconds_per_minute = 60
133        seconds_per_hour = 3600
134        seconds_per_day = 86400
135        seconds_per_week = 604800
136        seconds_per_month = 2419200
137        seconds_per_year = 29030400
138        time_units = [
139            (seconds_per_year, "y"),
140            (seconds_per_month, "mn"),
141            (seconds_per_week, "w"),
142            (seconds_per_day, "d"),
143            (seconds_per_hour, "h"),
144            (seconds_per_minute, "m"),
145            (second, "s"),
146            (millisecond, "ms"),
147            (microsecond, "us"),
148        ]
149        if not subsecond_resolution:
150            time_units = time_units[:-2]
151        time_string = ""
152        for time_unit in time_units:
153            unit_amount, num_seconds = divmod(num_seconds, time_unit[0])
154            if unit_amount > 0:
155                time_string += f"{int(unit_amount)}{time_unit[1]} "
156        if time_string == "":
157            return f"<1{time_units[-1][1]}"
158        return time_string.strip()

Returns num_seconds as a string with units.

Parameters
  • subsecond_resolution: Include milliseconds and microseconds with the output.
stats: str

Returns a string stating the currently elapsed time and the average elapsed time.