Measuring code block execution time in Python

Posted 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:

start = time.perf_counter_ns()
# your code
duration_ns = time.perf_counter_ns() - start

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:

with TimedBlock('critical section'):
    # your code

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 I find statsd appropriate for such use cases.

class TimedBlock:
     def __init__(self, name):
         self.__name = name
         self.__start = None
 
     def __enter__(self):
         self.__start = time.perf_counter_ns()
 
     def __exit__(self, *args):
         end = time.perf_counter_ns()
         elapsed_ns = end - self.__start
         elapsed_ms = int(elapsed_ns / 1000)
         statsd_client.timing(f'timed_block.{self.__name}', elapsed_ms)

In statsd, we get a bunch of critical sections stored under timed_block and we can examine the most problematic ones.

Did you find this useful?

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

I use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.