Created
July 18, 2024 07:05
-
-
Save izikeros/7173b5744b52e84f6986ceec117ad6e0 to your computer and use it in GitHub Desktop.
[timer decorator] Decorator that measure and print execution time #decorator #timer #elapsed-time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Usage example: | |
@timer_decorator | |
def sum_list(numbers): | |
return sum(numbers) | |
numbers = list(range(1, 1000000)) # Create a list of numbers from 1 to 999999 | |
result = sum_list(numbers) | |
print(f"Sum: {result}") | |
""" | |
def timer_decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
start_time = time.time() | |
result = func(*args, **kwargs) | |
elapsed_time = time.time() - start_time | |
print(f"{func.__name__} took {elapsed_time:.2f} seconds to execute.") | |
return result | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment