One-Line Timing in Python

Posted on Mon 19 August 2019 in technology

I'm generally a huge proponent of profiling code to discern its performance characteristics, but sometimes dragging a full blown profiler into code is a pain. What if you just want to see how much wall-clock time a particular piece of code takes to run?

I use the following snippet so frequently for simple timing that I've moved it into a utility library that gets sucked into substantially all of my projects:

import time

class Timer:
    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, *args):
        self.end = time.clock()
        self.interval = self.end - self.start
        print(self.interval)

When I need to time how long a piece of code takes to run, using it it's as simple as something like this:

with Timer():
    for i in range(100000):
        do_something(i)

Not much else to add here, other than the fact that I love context managers.