Consider the following example of a timer implemented as a context manager:
from contextlib import contextmanager import time @contextmanager def timer(label): start = time.time() try: yield finally: end = time.time() print(f'{label}: {end - start} seconds') # Usage: with timer('Model training'): # Your code block here, e.g., train your model
In this example, the `timer` function is decorated with `@contextmanager`, transforming it into a context manager. When you use this timer within a `with` statement, it automatically measures the time taken to execute the enclosed code block.
This feature proves exceptionally useful for profiling the performance of various parts of your codebase. For instance, in the context of machine learning, you can easily measure the duration of model training or inference without inserting cumbersome timing statements throughout your code.
By adopting Python's context manager and the `contextlib` module, you can streamline the process of performance profiling, making your code more readable and focused on its primary logic. Try incorporating this timer into your projects to gain valuable insights into the execution time of critical code segments.