Boa
Boa

Reputation: 2687

Best way to time a python function, and get that function's output?

To time a python function, the most common approach seems to involve the 'timeit' module, which returns the time that it took to run the function, but does not return the output of the function.

Is there a module which does the same thing as timeit, but which returns the output of the function, in addition to the running time, or is it necessary to implement that manually? If implementing this manually, what's a good timing function for this purpose, which is reasonably accurate, and which doesn't have a lot of overhead (options include, os.times(), datetime.now(), etc.)?

Upvotes: 1

Views: 827

Answers (2)

user1823
user1823

Reputation: 1111

You can try using time.time():

def timefunc(func):
    from time import time
    then = time()
    func()
    print time() - then

As such:

def foo():
    from sys import stdout
    from time import sleep
    for i in range(1, 11):
            stdout.write("\r%d" % i)
            stdout.flush()
            sleep(0.1)
    stdout.write("\n")

>>> timefunc(foo)
10
1.01269602776
>>> timefunc(foo)
10
1.00967097282
>>> timefunc(foo)
10
1.01678395271
>>> 

Upvotes: 1

manglano
manglano

Reputation: 844

Likely a number of approaches to this problem, but here are two you may consider:

  • Run the function and store its output in a variable. Print the time.clock time after the function completes, but immediately before returning the output stored at the variable. The time complexity of the return statement is negligible w/r/t the function.

  • The above approach may be inappropriate if you are, say, comparing several implementations for both correctness and runtime. In that case, consider returning the function's output and the time.clock output in a list, which can then be accessed, stored in a struct, etc. Again, the function itself will majorize vs. the list operations and return.

As per the comment, use time.clock to get processor time precision.

Upvotes: 1

Related Questions