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.

Create a stopwatch context manager in Python.

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}"

Usage

with Stopwatch() as stopwatch:
print("Hey")
print(stopwatch)
print("Ho!")
print("Let's")
print(stopwatch)
print("Go!")

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.

Output:

Starting stopwatch
Hey
Elapsed time 4.775000000000612e-05
Ho!
Let's
Elapsed time 7.953900000000347e-05
Go!
Finished in 8.804899999999977e-05
Written by Loek van den Ouweland on 2020-08-11.
Questions regarding this artice? You can send them to the address below.