Function to show time to execute another function

Steven D'Aprano steve at pearwood.info
Sun Jun 7 05:28:46 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


There is a lot of subtlety in timing functions on modern day computers. What
you measure there includes the time taken to lookup the names "function"
and "args" (although that ought to be very quick) and to expand out *args
(not quite so quick). 

More importantly, it will also be less accurate on Windows systems, and may
include time during which the operating system is running other background
tasks. It makes no attempt to allow for whether code is in the CPU cache or
not. And what if the garbage collector happens to run in the middle of your
test?

Timing code these days is subtle and complicated!

Depending on what function actually does, those complications may, or may
not, make a real difference. If function() does a lot of work (say, at
least one second) then what I have said is probably completely irrelevant
and you can ignore it. For those cases, your function is perfectly fine,
although I prefer to use a with statement interactively. Of course I can
still call a function, but I don't *have* to call a function.

Here is a simple example:

http://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/



But if your function takes less than, say, 1 millisecond, then your timing
results are probably just meaningless random numbers, affected more by the
other ten thousand processes running on your computer than by the Python
code itself.

In that case, you should learn how to use the timeit module. It's a little
complex, but worth it for timing small code snippets.


-- 
Steven




More information about the Python-list mailing list