A context manager is a class that implements two magical methods:
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:
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