This advertisement helps me to keep writing articles on this website

Create a stopwatch context manager in Python.

The perf_counter function can be used to measure elapsed time between two points in your code. A decorator can be used to create a stopwatch that measures how long it takes to execute a function. But what if you want to wrap just one ore more lines of code in a generic way? The answer is context managers. In this article, you learn how to create a context manager and how to use the with-keyword to time the speed of your code

A context manager is a class that implements two magical methods:

  1. enter (called just before executing the code in the with block)
  2. exit (called just after executing the code in the with block)

The enter method is used to store a time-stamp and returns the Stopwatch instance that is available via the stopwatch variable.

the exit method is the place where you can dispose stuff. Here it just prints the elapsed time.

import time

class Stopwatch:
    def __enter__(self):
        self.start = time.perf_counter()
        print("Starting stopwatch")
        return self

    def __exit__(self, *args):
        print("Finished in", time.perf_counter() - self.start)

    def __str__(self):
        return f"Elapsed time {time.perf_counter() - self.start}"


with Stopwatch() as stopwatch:

Since the Stopwatch instance is available in the with-block, you can use it to print elapsed time print(stopwatch) anywhere you want in your code.


Starting stopwatch
Elapsed time 4.775000000000612e-05
Elapsed time 7.953900000000347e-05
Finished in 8.804899999999977e-05
Written by Loek van den Ouweland on August 11, 2020. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.