Reputation: 79
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.
Upvotes: 6
Views: 6714
Reputation: 5486
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.
Upvotes: 11