|
| 1 | +import time |
| 2 | + |
| 3 | +class Timer: |
| 4 | + """ |
| 5 | + This class calculates the time taken by a piece of code. |
| 6 | +
|
| 7 | + Attributes |
| 8 | + ---------- |
| 9 | + start_time : float |
| 10 | + The start time of the block of code. |
| 11 | + end_time : float |
| 12 | + The end time of the block of code. |
| 13 | + elapsed_time : float |
| 14 | + The total time taken by the code block (in seconds). |
| 15 | +
|
| 16 | + Methods |
| 17 | + ------- |
| 18 | + __enter__(): |
| 19 | + Records the start time and enters the context. |
| 20 | + __exit__(exc_type, exc_val, exc_tb): |
| 21 | + Records the end time, calculates the execution time, and exits the context. |
| 22 | + __call__(task: str): |
| 23 | + Prints the name of the task being executed. |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self) -> None: |
| 27 | + """ |
| 28 | + Initializes an instance of Timer. |
| 29 | +
|
| 30 | + Returns: |
| 31 | + None |
| 32 | + """ |
| 33 | + print(f"Initializing {self.__class__.__name__}") |
| 34 | + self.start_time = None |
| 35 | + self.end_time = None |
| 36 | + self.elapsed_time = None # Initialize elapsed_time attribute |
| 37 | + |
| 38 | + def __enter__(self) -> "Timer": |
| 39 | + """ |
| 40 | + Starts the timer by recording the start time. |
| 41 | +
|
| 42 | + Returns: |
| 43 | + Timer: Returns itself |
| 44 | + """ |
| 45 | + print(f"Entering {self.__class__.__name__}") |
| 46 | + self.start_time = time.time() |
| 47 | + return self |
| 48 | + |
| 49 | + def __exit__(self, exc_type, exc_val, exc_tb) -> bool: |
| 50 | + """ |
| 51 | + Stops the timer, calculates the execution time, and prints it. |
| 52 | +
|
| 53 | + Args: |
| 54 | + exc_type: The type of exception raised, if any. |
| 55 | + exc_val: The value of the exception, if any. |
| 56 | + exc_tb: The traceback of the exception, if any. |
| 57 | +
|
| 58 | + Returns: |
| 59 | + bool: True, to suppress any exception that occurs within the context. |
| 60 | + """ |
| 61 | + print(f"Exiting {self.__class__.__name__}") |
| 62 | + self.end_time = time.time() |
| 63 | + self.elapsed_time = self.end_time - self.start_time # Calculate and store elapsed time |
| 64 | + print(f"Execution time: {self.elapsed_time:.4f} seconds") |
| 65 | + return True |
| 66 | + |
| 67 | + def __call__(self, task: str) -> None: |
| 68 | + """ |
| 69 | + Prints the name of the task being executed. |
| 70 | +
|
| 71 | + Args: |
| 72 | + task (str): A string representing the task name. |
| 73 | + """ |
| 74 | + print(f"Calling {task}") |
| 75 | + return None |
| 76 | + |
| 77 | + |
| 78 | +def main() -> None: |
| 79 | + with Timer() as calc: |
| 80 | + for i in range(10 * 1000): |
| 81 | + i ** 0.254444 |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + main() |
0 commit comments