Member-only story
Aggregate code timing in Python
2 min readJul 20, 2022
Consolidated stats on code timing in a function
There are many ways to get how much time a function takes in Python. Here is an easy decorator implementation to check how much time a function takes.
from functools import wraps
import time
def timeit(func):
@wraps(func)
def timeit_wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
total_time = end_time - start_time
print(f'Function {func.__name__}{args} {kwargs} took {total_time:.4f} seconds')
return result
return timeit_wrapper@timeit
def my_func():
# do stuff
This decorator can be used by decorating a function to get the time spent. What if you want to aggregate this timing data in a timeframe, like how many times this function has been called, and what the maximum time is taken, for that, we need to use a library called codetiming. Here is a sample use case:
# pip install codetiming
# pip install humanfriendly
from codetiming import Timer
from humanfriendly import format_timespan
from loguru import logger
@Timer(name="my_func", text=lambda secs: f"my_func elapsed time: {format_timespan(secs)}")
def my_func():
...