IPython: How to save timeit values for each iteration
Asked Answered
D

1

6

I'm new to Python and trying to plot the computational speeds of two functions. For example, having defining two functions (see below), how can I return the time for each iteration using the timeit function in IPython/Jupyter?

def func1(x) : 
    return x*x
def func2(x) :
    return x+x
%timeit for x in range(100) : func1(x)
%timeit for x in range(100) : func2(x)

I read https://ipython.org/ipython-doc/3/interactive/magics.html that I can use '-o' to "return a TimeitResult that can be stored in a variable to inspect the result in more details."

But how do I save it to a variable say 'func1_time' and how can I read the time for each iteration? My goal is to plot x vs time for both functions.

Any help will be much appreciated. Thanks.

Dissever answered 11/1, 2018 at 11:24 Comment(0)
B
11

You simply do the following:

func1_time = %timeit -o func1(10)

You can access the timing for each iteration by

func1_time.timings

and total time taken for each loop by

func1_time.all_runs

Note that your loops are unneccessary, since %timeit executes your code N times in a loop and iterates this loop r times.


Update

If you need the timings for different argumets x, you may try the following:

func1_time = []
for i in [10, 100, 1000]:
    foo =  %timeit -o func1(x)
    func1_time.append(foo)

Then func1_time[0].timings holds the timings for func1(10).

If you do so, I recommend specifying the r and N options, since %timeit adapts the number of loops to the complexity of the problem. The means, the longer it takes to execute a function on time, the fewer loops are run.

Baudin answered 11/1, 2018 at 11:39 Comment(4)
Thanks MaxPowers! Just so I understand fully, the first line of your code allows %timeit to measure the time it takes to evaluate func1 @ 10 right? I'm trying to evaluate the func1(1), func1(2), ...., func1(100) and compare the times to that of func2.Dissever
@Tim That is right. Given the functions you provided, the argument does not matter. The time it takes to add two scalars is independent of their actual values. So, there is no difference between %time func1(1) and %time func1(10032).Baudin
Thanks for clarifying. I was just using these functions as an example, my functions are actually dealing with square matrices, with the input, x being the size. As x increases, the computational times should get distinctly larger. In this case, I would like to change the input. Is that what you meant when you mentioned the N times and r iterations?Dissever
should it be func1(i) instead of func1(x)Copier

© 2022 - 2024 — McMap. All rights reserved.