1

I know I can use this

from timeit import timeit
test = lambda f: timeit(lambda:f(100), number=1)
t1 = test(hello)

To time how long it takes the hello function to run with argument 100. But let's say my hello function returns the string 'world' and I want to store that returned value and also have to the time it took to execute.

Can that be done?

Juicy
  • 11,840
  • 35
  • 123
  • 212
  • What is it you're trying to achieve here? If you're setting `number=1`, `timeit` probably isn't the right tool for you. – jonrsharpe Oct 12 '14 at 17:14
  • @jonrsharpe I want to time how long it takes to run `hello(100)` once. This method was the top answer on the post I got it from. Could you suggest which other method you would use please? I don't understand the down vote... – Juicy Oct 12 '14 at 17:16
  • 2
    And what will you be doing with the return value? If you just want to ensure it's what you expect, consider `assert`. – jonrsharpe Oct 12 '14 at 17:18
  • @jonrsharpe For my lab my lecturer is asking that we time all our functions during the actual run. This is not just to check performance. I need to time my function AND use it's results as arguments for later functions in the program. – Juicy Oct 12 '14 at 17:23
  • 1
    You likely want something like this - http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script - Voting to close your question as a duplicate – David Oct 12 '14 at 17:25
  • Have you tried to write a function that returns a tuple or array so that you get a return of `(functionResult, timeResult)` ? – Paul Oct 12 '14 at 17:26

1 Answers1

4

If you just want to time specific calls to specific functions, you can do the following. This will get you the exact time of one run. However, you probably just want to use timeit or profile to get a more exact picture of what your program is doing. Those tools aggregate multiple runs to get a more accurate average case result.

Make a function that takes a function to call, records the time, then runs the function and returns the value and time delta.

import time

def timed(func, *args, **kwargs):
    start = time.time()
    out = func(*args, **kwargs)
    return out, time.time() - start

def my_func(value):
    time.sleep(value)
    return value

print(timed(my_func(5)))  # (5, 5.0050437450408936)
davidism
  • 121,510
  • 29
  • 395
  • 339