To measure the time elapsed in a function using a decorator in Python, you can use the time module or the more precise timeit.default_timer for timing. A decorator is a great way to add functionality (like timing) without modifying the original function's code.
Here’s an elegant and reusable implementation of a timing decorator:
Code Example
import time
from functools import wraps
def timer_decorator(func):
"""
A decorator to measure the execution time of a function.
"""
@wraps(func) # Preserves the metadata of the original function
def wrapper(*args, **kwargs):
start_time = time.perf_counter() # High-resolution timer
result = func(*args, **kwargs) # Call the original function
end_time = time.perf_counter()
elapsed_time = end_time - start_time
print(f"Function '{func.__name__}' executed in {elapsed_time:.6f} seconds.")
return result
return wrapper
# Example usage of the decorator
@timer_decorator
def example_function(n):
"""
Example function that simulates some work by sleeping.
"""
time.sleep(n)
return f"Slept for {n} seconds."
# Test the decorated function
if __name__ == "__main__":
result = example_function(2)
print(result)
Explanation of the Code
-
Decorator Function (timer_decorator):
- The decorator takes a function (
func) as input and returns a new function (wrapper).
- Inside the
wrapper, the timing logic is implemented:
- Start time is recorded using
time.perf_counter(), which provides high-resolution timing suitable for measuring short durations.
- The original function is called with its arguments (
*args and **kwargs).
- End time is recorded after the function completes.
- The elapsed time is calculated and printed in a human-readable format.
-
Preserving Metadata:
- The
@wraps(func) decorator from functools ensures that the metadata (e.g., __name__, __doc__) of the original function is preserved in the wrapped function.
-
Usage:
- The
@timer_decorator syntax is used to apply the decorator to any function.
- When the decorated function is called, the timing information is automatically printed.
Output Example
If you run the above code, the output will look like this:
Function 'example_function' executed in 2.002345 seconds.
Slept for 2 seconds.
Advantages of Using This Approach
- Reusability: The decorator can be applied to any function without modifying its internal logic.
- Separation of Concerns: Timing logic is separated from the core functionality of the function.
- Precision:
time.perf_counter() provides high-resolution timing, making it suitable for both short and long durations.
This implementation is clean, professional, and adheres to best practices for writing decorators in Python.