The timer decorator is a popular example of using decorators in Python. It's a simple decorator that adds timing functionality to a function, allowing you to measure the execution time of the function.
Here's an example of a timer decorator:
import timedef timer_decorator(func): def wrapper(*args, **kwargs): start_time = time.perf_counter() result = func(*args, **kwargs) end_time = time.perf_counter() print(f"Elapsed time: {end_time - start_time:.6f} seconds") return result return wrapper |
This decorator takes a function as an argument and returns a new function that wraps the original function with timing functionality. When the new function is called, it records the start time, calls the original function, records the end time, calculates the elapsed time, and prints it to the console.
To use this decorator to time a function, simply apply it to the function you want to time:
@timer_decoratordef my_function(): # Code to be timed here passmy_function() |
In this example, the @timer_decorator syntax applies the timer_decorator decorator to the my_function() function. When the function is called, the decorator will add timing functionality to it and print the elapsed time to the console.
Using a timer decorator like this can be useful when you need to time the execution of multiple functions. Instead of adding timing code to each function individually, you can simply apply the decorator to each function you want to time. This keeps the timing code separate from the function code, making it easier to maintain and modify.