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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With