[Python-ideas] Timer that starts as soon as it is imported
Devin Jeanpierre
jeanpierreda at gmail.com
Wed May 27 14:52:17 CEST 2015
On Wed, May 27, 2015 at 5:29 AM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> On May 27, 2015, at 05:18, Steven D'Aprano <steve at pearwood.info> 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
More information about the Python-ideas
mailing list