Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: How to save timeit values for each iteration

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.

like image 567
TimEckorote Avatar asked Jan 11 '18 11:01

TimEckorote


People also ask

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.

What is %% capture in Python?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. from __future__ import print_function import sys. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

What is% timeit?

timeit is used to measure the execution time for the small python code snippets. This module runs the code a million times (by default) to get the most precise value for the code execution time​.

What is IPython command?

IPython bridges this gap, and gives you a syntax for executing shell commands directly from within the IPython terminal. The magic happens with the exclamation point: anything appearing after ! on a line will be executed not by the Python kernel, but by the system command-line.


1 Answers

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.

like image 193
MaxPowers Avatar answered Nov 14 '22 22:11

MaxPowers