[Python-ideas] Timing hefty or long-running blocks of code

Masklinn masklinn at masklinn.net
Sat Jun 1 20:15:00 CEST 2013


On 2013-06-01, at 17:16 , Ron Adam wrote:

> 
> 
> On 06/01/2013 05:50 AM, Masklinn wrote:
>> A more general version can be achieved through timeit.Timer, though it's
>> got more boilerplate and as far as I know there's no example of it in
>> the documentation:
>> 
>> @timeit.Timer
>> def foo():
>>     do_this()
>>     do_that()
>> print foo.timeit(1)
>> 
>> On the other hand it allows repeated benching to try and refine the
>> iterations count.
>> 
>> Maybe context-management could simply be added to timeit.Timer,
>> rather than be a separate object?
> 
> I like the decorator variation.
> 
> +1 for adding it to timeit.
> 
> 
> 
> I would like to be able to specify the maximum count to time, and to be able to specify where to send the output.
> 
> 
> 
> function_timer = timeit.FunctionTimer(count=3, file=sys.stderr)
> 
> 
> @function_timer
> def foo():
>    ...
> 
> Which would print ...
> 
> Foo timer 1/3: n seconds
> Foo timer 2/3: n seconds
> Foo timer 3/3: n seconds
> 
> It would only time 'count' times through the function.
> 
> A function timer like this requires minimal changes to the code and can be pasted in or commented out as needed.

FWIW that can also be achieved by using timeit.Timer as a decorator:
simply call Timer.repeat afterwards instead of Timer.timeit, it defaults
to repeat=3 (which corresponds to your count=3) and returns a list of
results.

So

@timeit.Timer
def foo():
    do_this()
    do_that()
print foo.repeat(repeat=3, number=1)

will print a list of 3 elements, each of which corresponds to running
the function once.

> For me, timing a function is the most common type of timing I do in real programs.

All of timeit's stuff can take functions instead of statement strings,
both are supported.


More information about the Python-ideas mailing list