Last active
August 27, 2020 05:20
-
-
Save ryanbehdad/7996fe6d708e3dffb4a2b2ad126201ae to your computer and use it in GitHub Desktop.
Python decorators
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 functools | |
import time | |
def readable_time(t): | |
a = '' | |
if t < 1: | |
a = f'{t:.2f} sec' | |
elif t < 60: | |
a = f'{t:.0f} sec' | |
elif t < 3600: | |
a = f'{t//60:.0f} min, {t%60:.0f} sec' | |
else: | |
a = f'{t//3600:.0f} hour, {(t-3600*(t//3600))//60:.0f} min, {t%60:.0f} sec' | |
return a | |
def timer(func): | |
"""Print the runtime of the decorated function""" | |
@functools.wraps(func) | |
def wrapper_timer(*args, **kwargs): | |
start_time = time.perf_counter() | |
value = func(*args, **kwargs) | |
end_time = time.perf_counter() | |
run_time = end_time - start_time | |
print(f"Finished {func.__name__!r} in {readable_time(run_time)}") | |
return value | |
return wrapper_timer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment