Skip to content

Instantly share code, notes, and snippets.

@rcarlier
Created May 3, 2025 04:58
Show Gist options
  • Save rcarlier/ebc72b7b38a5a2fea457474ffb279beb to your computer and use it in GitHub Desktop.
Save rcarlier/ebc72b7b38a5a2fea457474ffb279beb to your computer and use it in GitHub Desktop.
python decorator to measure the execution time of a function
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not hasattr(wrapper, 'total_time'):
wrapper.total_time = 0
_start = time.perf_counter()
_result = func(*args, **kwargs)
_end = time.perf_counter()
_duration = _end - _start
wrapper.total_time += _duration
print(f"fn '{func.__name__}' = {_duration:.4f}", end=" - ")
print(f"cumul : {wrapper.total_time:.4f}")
return _result
return wrapper
@timer
def test():
time.sleep(1)
test() # fn 'test' = 1.0045 - cumul : 1.0045
test() # fn 'test' = 1.0030 - cumul : 2.0075
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment