Fun with Context Managers

Sometimes I need a simple stop watch in my Python scripts to find out how expensive my code is in wall clock time. The problem is trivial to solve, but I thought I'd give it a try using Python's with statement and a context manager.

Previously, my code looked like this:

t = start()
# do something expensive
stop(t)

The start() function records the start time and the stop() function prints the duration.

For simple things it works, but I have to pass the start time around, and if the statements raise exceptions it won't print the end time. Also, if I measure multiple things I have to be careful not to confuse the variables keeping the recorded time.

My initial idea to improve this was to use decorators, but then I'd have to wrap my block of code in a function. Not what I wanted. But then I remembered Python's with statement. I implemented a custom context manager (it's quite simple using contextlib) and now my code looks like this:

with stopwatch():
    # some statements

The context manager prints the execution time and whether the execution was successful. In my implementation, you can assign a name to your stop watch and decide if exceptions should be swallowed or passed through.

social