Last active
April 16, 2024 14:08
-
-
Save mahdiPourkazemi/e7737bcd19bb0dcadd7276e58a052fe4 to your computer and use it in GitHub Desktop.
python decorator usage example
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 | |
import functools | |
def timer(func): | |
"""print the runtime of the decorated function""" | |
functools.wraps(func) | |
def timer_wraper(*args,**kargs): | |
#get time before call func | |
start_time = time.perf_counter() | |
#call func | |
value = func(*args,**kargs) | |
#get time after call func | |
end_time = time.perf_counter() | |
#calculate run time | |
run_time = end_time - start_time | |
print(f'Finished {func.__name__!r} in {run_time:.4f} secs') | |
return value | |
return timer_wraper | |
#usage example | |
@timer | |
def waste_some_time(num_time): | |
for _ in range(num_time): | |
sum([i**2 for i in range(10000)]) | |
waste_some_time(100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment