|
| 1 | +import time |
| 2 | + |
| 3 | +class Timer: |
| 4 | + """ |
| 5 | + A context manager that measures the elapsed time of a code block. |
| 6 | +
|
| 7 | + This class allows you to measure the time taken to execute |
| 8 | + a block of code using the context management protocol. |
| 9 | + It records the start time when entering the context and |
| 10 | + the end time when exiting the context, allowing you to |
| 11 | + calculate and print the elapsed time. |
| 12 | +
|
| 13 | + Attributes: |
| 14 | + start_time (float): The time when the timer starts. |
| 15 | + end_time (float): The time when the timer ends. |
| 16 | +
|
| 17 | + Example: |
| 18 | + >>> with Timer() as timer: |
| 19 | + ... time.sleep(2) |
| 20 | + ... |
| 21 | + Elapsed time: 2.0000 seconds |
| 22 | + """ |
| 23 | + def __init__(self): |
| 24 | + """ |
| 25 | + Initializes the Timer with start and end times set to None. |
| 26 | +
|
| 27 | + Attributes: |
| 28 | + start_time (float): The time when the timer starts (initially None). |
| 29 | + end_time (float): The time when the timer ends (initially None). |
| 30 | + """ |
| 31 | + self.start_time = None |
| 32 | + self.end_time = None |
| 33 | + |
| 34 | + def __enter__(self): |
| 35 | + """ |
| 36 | + Starts the timer by recording the current time. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Timer: The Timer instance, allowing access to start and end times. |
| 40 | + """ |
| 41 | + self.start_time = time.time() |
| 42 | + return self |
| 43 | + |
| 44 | + def __exit__(self, exc_type, exc_value, traceback): |
| 45 | + """ |
| 46 | + Stops the timer and calculates the elapsed time. |
| 47 | +
|
| 48 | + This method is called when exiting the context. It calculates |
| 49 | + the elapsed time and prints it. |
| 50 | +
|
| 51 | + Args: |
| 52 | + exc_type: The exception type (if an exception occurred). |
| 53 | + exc_value: The exception value (if an exception occurred). |
| 54 | + traceback: The traceback object (if an exception occurred). |
| 55 | +
|
| 56 | + Returns: |
| 57 | + bool: Returns False to propagate any exceptions that occurred. |
| 58 | + """ |
| 59 | + self.end_time = time.time() |
| 60 | + elapsed_time = self.end_time - self.start_time |
| 61 | + print(f"\n\nElapsed time: {elapsed_time:.4f} seconds") |
| 62 | + return False |
0 commit comments