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

Ron Adam ron3200 at gmail.com
Sat Jun 1 17:16:04 CEST 2013



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.



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


Cheers,
    Ron











More information about the Python-ideas mailing list