Created
September 28, 2023 16:30
-
-
Save chemacortes/fd7341975b00f5da786bcf1a02ada892 to your computer and use it in GitHub Desktop.
Decorator that calc the last execution time of a function. The result is added as a new function attribute named 'last_execution_time'.
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_decorator(func): | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
start = time.time_ns() | |
res = func(*args, **kwargs) | |
end = time.time_ns() | |
wrapper.last_execution_time = end - start | |
return res | |
return wrapper | |
if __name__ == "__main__": | |
@timer_decorator | |
def fact(n: int) -> int: | |
res = 1 | |
for i in range(2, n+1): | |
res *= i | |
return res | |
N = 100000 | |
fact_N = fact(N) | |
print(f"Calculated fact({N}) in {fact.last_execution_time/1000000} ms.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment