Python has a convenient timing function called timeit
, which is also avaailable as magic in Ipython/Jupyter notebooks
Can use this to measure the execution time of small code snippets.
import timeit
and supply code snippet as a string%timeit
By default, %timeit
repeats the code 3 times and outputs the best time. It also tells you how many iterations it ran the code per repeat.
You can specify the number of repeats and the number of iterations per repeat.
%timeit -n <iterations> -r <repeats> <code_snippet>
If you want to run multiple lines of code in a cell block then you need to use:
%%timeit -n <iterations> -r <repeats>
<code_snippet1>
<code_snippet2>
`
See
%timeit?
for more informationFirst as always we must import numpy
:
import numpy as np
Let's create ourselves an array as before and change their shape.
nd = np.arange(100).reshape((10,10))
We can use magic %timeit
to time hold long it takes to access elements of the array, and explore which method for accessing elements of an array is quicker.
# accessing element of 2d array
%timeit -n 10000000 -r 3 nd[5][5]
%timeit -n 10000000 -r 3 nd[(5,5)]
All accesses are not equal. If we want to time multiple lines of code the we can use the %%timeit
with default settings:
%%timeit
nd[5][5]
nd[(5,5)]
Though note that now we just get time time for the entire code block. Using the default settings can be good when we don't know how long a code block will take to execute, as timeit
will decide how many instances or loops to run, to get reasonable statistics in reasonable time.