Function to show time to execute another function

Steven D'Aprano steve at pearwood.info
Sun Jun 7 05:51:15 EDT 2015


On Sun, 7 Jun 2015 04:39 pm, Cecil Westerhof wrote:

> Sometimes I just want to know how much time a function takes, but at
> the same time I also want the result of the function. For this I wrote
> the following function:
>     def time_test(function, *args):
>         startTime   = time.time()
>         results     = function(*args)
>         endTime     = time.time()
>         print('It took {0} seconds'.format(endTime - startTime))
>         return results

Oh, I forgot to mention... 

This has the disadvantage that it only prints the time, you cannot collect
it for further processing. (Well, not easily -- you could always shadow the
print built-in, then parse the string... ugggh, that's horrible.)

Using the Timer with statement I linked to earlier, you can easily collect
both the time and the calculated result:

with Timer(verbose=False) as t:
    do_this()
    do_that()
    result = something_else()

time_taken = t.interval
print(result, "took", time_taken)

Even the verbose=False flag is optional, if you leave it out the timing
result will be printed as usual, and you can still capture the time using
t.interval afterwards.

If you are interested, I have a more advanced version of that Timer which I
use almost every day. It works in Python 2.4 through 3.3, I expect it to
work in 3.4 and 3.5 as well, and is extensively tested in CPython and seems
to work in Jython and IronPython as well.


Oh, and to give you an idea of just how large the individual timing
fluctuations of small code snippets can be, here is an example running
under IronPython 2.6:

>>> from timer import Stopwatch
>>> with Stopwatch():
...     x = 12
...     y = x/3
...
time taken: 0.019135 seconds
>>> with Stopwatch():
...     x = 12
...     y = x/3
...
elapsed time is very small; consider using timeit.Timer for micro-timings of
small code snippets
time taken: 0.000114 seconds


The first run was over 160 times slower than the second run.



-- 
Steven




More information about the Python-list mailing list