In IPython, we can profile small snippets of code using timeit
. We can also profile a larger script. We will show both approaches.
First, we will time a small snippet:
Start IPython in
pylab
mode:$ ipython --pylab
Create an array containing 1000 integer values between 0 and 1000:
In [1]: a = arange(1000)
Measure the time taken for searching "the answer to everything"—42, in the array. Yes, the answer to everything is 42. If you don't believe me, read http://en.wikipedia.org/wiki/42_%28number%29:
In [2]: %timeit searchsorted(a, 42) 100000 loops, best of 3: 7.58 us per loop
Profile the following small script that inverts a matrix of varying size containing random values. The
.I
attribute (that's an uppercase I) of a NumPy matrix represents the inverse of that matrix:import numpy as np def invert(n): a = np.matrix(np.random.rand(n, n)) return a.I sizes = 2 ** np.arange(0, 12) for n in sizes: invert(n)
Time this code as follows:
In [1]: %run -t invert_matrix...