67. Decorators for Timing Functions
Decorators for Timing Functions: Measuring Execution Time
A decorator in Python is a function that wraps another function to modify its behavior. One useful application of decorators is to measure the execution time of functions. This can be useful for performance monitoring or profiling. Below is an example of how to create a decorator that measures the execution time of a function.
1. Basic Timing Decorator
This decorator will measure the time it takes for a function to execute and print the result.
Copy
import time
# Timing decorator
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time() # Record start time
result = func(*args, **kwargs)
end_time = time.time() # Record end time
print(f"Execution time of {func.__name__}: {end_time - start_time:.4f} seconds")
return result
return wrapper
# Example function to measure
@timing_decorator
def slow_function():
time.sleep(2) # Simulating a time-consuming operation
return "Done"
# Call the function
slow_function()Output:
Copy
2. Decorator with Arguments
If you want to add functionality like logging the time for a list of functions or conditional execution, you can add parameters to the decorator.
Copy
Output:
Copy
3. Timing Decorator for Multiple Functions
You can use a decorator to time multiple functions without repeating the timing logic.
Copy
Output:
Copy
4. Using functools.wraps for Preserving Function Metadata
When using decorators, the metadata of the wrapped function (like its name and docstring) may be lost. To avoid this, use functools.wraps() to preserve the original function's attributes.
Copy
Output:
Copy
5. Decorator for Asynchronous Functions
If your function is asynchronous, you can also use a timing decorator with asyncio.
Copy
Output:
Copy
6. Using Time in Nanoseconds
To measure the execution time with more precision, you can use time.perf_counter() which provides a higher-resolution timer.
Copy
Output:
Copy
7. Timing Function with Return Value
The decorator can also return the function’s result after logging the execution time.
Copy
Output:
Copy
8. Using Timing Decorators with Function Arguments
You can also pass arguments into the decorator, like logging the time for specific types of functions.
Copy
Output:
Copy
9. Decorator for Profiling Multiple Functions
Use the decorator for profiling multiple functions in your code.
Copy
Output:
Copy
10. Combining Multiple Decorators
You can combine timing decorators with other decorators, for example, logging.
Copy
Output:
Copy
By using decorators to measure execution time, you can efficiently monitor the performance of your functions, especially when working with time-consuming tasks. The decorator pattern is a powerful tool in Python, and this technique helps keep the code clean and reusable.
Last updated