Skip to content

Instantly share code, notes, and snippets.

@chemacortes
Created September 28, 2023 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chemacortes/fd7341975b00f5da786bcf1a02ada892 to your computer and use it in GitHub Desktop.
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'.
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