timeit eats return value

1.9k Views Asked by At

I want to measure execution time of a function on the cheap, something like this:

def my_timeit(func, *args, **kwargs):
    t0 = time.time()
    result = func(*args, **kwargs)
    delta = time.time() - t0
    return delta, result

def foo():
    time.sleep(1.23)
    return 'potato'

delta, result = my_timeit(foo)

But I want to use timeit, profile or other built-in to handle whatever are the common pitfalls due to platform differences, and it would probably be also better to get the actual execution time not the wall time.

I tried using timeit.Timer(foo).timeit(number=1) but the interface seems to obscure the return value.

2

There are 2 best solutions below

2
On BEST ANSWER

This is my current attempt. But I would welcome any suggestions, because this feels too hacky and could probably do with improvement.

import time
from timeit import Timer

def my_timeit(func, *args, **kwargs):
    output_container = []
    def wrapper():
        output_container.append(func(*args, **kwargs))
    timer = Timer(wrapper)
    delta = timer.timeit(1)
    return delta, output_container.pop()

def foo():
    time.sleep(1.111)
    return 'potato'

delta, result = my_timeit(foo)

edit: adapted to work as a decorator below:

def timeit_decorator(the_func):

    @functools.wraps(the_func)
    def my_timeit(*args, **kwargs):
        output_container = []
        def wrapper():
            output_container.append(the_func(*args, **kwargs))
        timer = Timer(wrapper)
        delta = timer.timeit(1)
        my_timeit.last_execution_time = delta
        return output_container.pop()

    return my_timeit
1
On

How about

>>time python yourprogram.py < input.txt

This is the output for a python script I ran

[20:13:29] praveen:jan$ time python mtrick.py < input_mtrick.txt 
3 3 9
1 2 3 4
real    0m0.067s
user    0m0.016s
sys 0m0.012s