Evaluating the time taken by a command in IPython
The %timeit
magic and the %%timeit
cell magic (which applies to an entire code cell) allow us to quickly evaluate the time taken by one or several Python statements. The next recipes in this chapter will show methods for more extensive profiling.
How to do it...
We are going to estimate the time taken to calculate the sum of the inverse squares of all positive integer numbers up to a given n
.
- Let's define
n
:>>> n = 100000
- Let's time this computation in pure Python:
>>> %timeit sum([1. / i**2 for i in range(1, n)]) 21.6 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
- Now, let's use the
%%timeit
cell magic to time the same computation written on two lines:>>> %%timeit s = 0. for i in range(1, n): s += 1. / i**2 22 ms ± 522 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
- Finally, let's time the NumPy version of this computation...