Link
Link

Reputation: 61

Timeit with range of int as parameter for function

I want to compare execution times of functions with timeit with a range of (0,30) as parameters, so I can store the exection time of each call with a different parameter in a list. This repeat function calls (as per default) the function 5 times, instead of returning the times for all parameters 0 to 30

times = timeit.repeat("for x in range(30): foo(x)", "from __main__ import foo",
                      number=100)

So how can I pass the parameters to the function and get the execution time for each of them?

Upvotes: 0

Views: 149

Answers (1)

Grismar
Grismar

Reputation: 31389

Here's an example:

from time import sleep
from timeit import timeit


def foo(x):
    sleep(1/(x+1))


n = 1
print(list([timeit(lambda: foo(x), number=n) / n] for x in range(30)))

Result:

[[1.0116304], [0.5029303], [0.34732699999999994], [0.2513573], etc.]

It runs timeit for foo(0), then foo(1), etc. It runs it n times (you could set it to a 100) and it divides the outcome by n to obtain the time taken by each run on average.

The list() is there because it will just print the generator object in there otherwise - square brackets would also work.

I think the lambda: is the part you were after. It allows you to pass in the parameter you want to pass in without having to change how timeit is called, as timeit expects a function to call to be passed in, so you can't pass in foo(x) (since that would just evaluate to None, the function result).

Upvotes: 1

Related Questions