Kamil Choudhury

#define ZERO -1 // oh no it's technology all the way down

One-Line Timing in Python

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

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):

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