Last active
August 9, 2021 10:57
-
-
Save Rustam-Z/e765aa24549d5980cc281c51e9c1fe29 to your computer and use it in GitHub Desktop.
A decorator that prints how long a function took to run.
This file contains 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
import time | |
from functools import wraps | |
def timer(func): | |
"""A decorator that prints how long a function took to run.""" | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
# When wrapper() is called, get the current time. | |
t_start = time.time() | |
# Call the decorated function and store the result. | |
result = func(*args, **kwargs) | |
# Get the total time it took to run, and print it. | |
t_total = time.time() - t_start | |
print('{} took {}s'.format(func.__name__, t_total)) | |
return result | |
return wrapper | |
@timer | |
def sleep_n_seconds(n): | |
time.sleep(n) | |
sleep_n_seconds(5) # sleep_n_seconds took 5.0050950050354s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment