Created
May 3, 2025 04:58
-
-
Save rcarlier/ebc72b7b38a5a2fea457474ffb279beb to your computer and use it in GitHub Desktop.
python decorator to measure the execution time of a function
This file contains hidden or 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 | |
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