Aggregate Code timing in Python
Aggregate Code timing in Python
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.
=
=
=
= -
return
return
# 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
# pip install loguru
...
=
# clears all the timer data
This will find the aggregated time spent by my_func
. Let’s go through what each one of them will log:
- count: Number of times the function has been called.
- total: Sum of all the seconds elapsed in the function
- max: Maximum time spent on a single flow
- min: Minimum time spent on a single flow
- mean: The average of all the time spent on that function
- median: The median of all elapsed time
- stdev: The standard deviation of all elapsed time
At the end Timer.timers.clear()
clears the data stored In memory and starts from fresh for the next iteration.
Do you want to use an in-memory LRU cache with a timeout, you may check out this article:
- Cache heavy computation functions with a timeout value
- How I solved a memory leak caused by this codetiming library: Patching a memory leak
I post on Python programming on my Twitter handle, you can follow me @soumendrak_.