On Wed, May 27, 2015 at 5:29 AM, Andrew Barnert via Python-ideas
On May 27, 2015, at 05:18, Steven D'Aprano
wrote: I have a timer context manager which is designed for timing long-running code. You write the code in a "with" block:
with Stopwatch(): do_this() do_that()
The context manager starts the timer when you enter, and stops it when you leave. By default it prints the time used, but you can easily suppress printing and capture the result instead. I've been using this for a few years now, and it works well. The only downside is that it works too well, so I'm tempted to use it for micro code snippets, so I have it print a warning if the time taken is too small:
py> with Stopwatch(): ... n = len("spam") ... elapsed time is very small; consider using timeit.Timer for micro-timings of small code snippets time taken: 0.000010 seconds
That's a clever idea. I have something very similar, and I sometimes find myself abusing it that way...
Why not use an iterable stopwatch that measures time between calls to __next__/next? for _ in Stopwatch(): .... -- Devin