Measuring code block execution time in PythonPosted on Nov 08, 2021, 1 minute to read.
In this quick note, let’s see how to measure the time a code block gets executed in Python.
The simple way to do so in Python is to run:
However, I find this too complex for adding in production code. It involves at least two lines without even storing the result. So, I have a class that I use in the following manner that I find simple enough for maintainability:
How does it work under the hood? When we enter the
timed block, before the code starts, we store the
perf counter as above. When the code is done executing, we compute elapsed time and store it in
statsd - you can do something else, but
statsd appropriate for such use cases.
statsd, we get a bunch of critical sections stored under
timed_block and we can examine the most problematic ones.