|
| 1 | +import time |
| 2 | +from typing import Optional, Callable |
| 3 | + |
| 4 | +class Timer: |
| 5 | + def __init__(self, log: bool = True, callback: Optional[Callable[[float], None]] = None): |
| 6 | + """ |
| 7 | + Initialize the Timer with optional logging and a callback function. |
| 8 | + :param log: If True, logs start and end messages; if False, remains silent. |
| 9 | + :param callback: An optional function to call with the elapsed time when exiting. |
| 10 | + """ |
| 11 | + self.log = log |
| 12 | + self.callback = callback |
| 13 | + self.start_time = None |
| 14 | + self.end_time = None |
| 15 | + self.elapsed_time = None |
| 16 | + if self.log: |
| 17 | + print(f"{self.__class__.__name__} initialized.") |
| 18 | + |
| 19 | + def __enter__(self) -> "Timer": |
| 20 | + """ |
| 21 | + Start the timer upon entering the context. |
| 22 | + """ |
| 23 | + self.start_time = time.time() |
| 24 | + if self.log: |
| 25 | + print(f"{self.__class__.__name__} started.") |
| 26 | + return self |
| 27 | + |
| 28 | + def __exit__(self, exc_type, exc_val, exc_tb) -> bool: |
| 29 | + """ |
| 30 | + Stop the timer upon exiting the context and calculate the elapsed time. |
| 31 | + Calls the callback function if provided. |
| 32 | + """ |
| 33 | + self.end_time = time.time() |
| 34 | + self.elapsed_time = self.end_time - self.start_time |
| 35 | + if self.log: |
| 36 | + print(f"{self.__class__.__name__} ended. Elapsed time: {self.elapsed_time:.4f} seconds") |
| 37 | + |
| 38 | + # If a callback is provided, call it with the elapsed time |
| 39 | + if self.callback: |
| 40 | + self.callback(self.elapsed_time) |
| 41 | + |
| 42 | + # Return False to allow any exceptions to propagate |
| 43 | + return False |
0 commit comments