Often, when we are working in the Python REPL, we would like to be able to quickly and easily benchmark a line of code or a function. IPython makes this possible through a magic function called timeit
.
Perform the following set of steps to try out %timeit
to profile the code:
Open up a new terminal and change to the direction of the
asa.py
source code.Fire up IPython by typing the following:
ipython
Let's see how fast or slow the built-in square root function is, as follows:
In [1]: import math In [2]: %timeit math.sqrt(10000)
This should produce output similar to the following:
10000000 loops, best of 3: 166 ns per loop
We see that
%timeit
, due to the rapid execution of themath.sqrt()
method, tested the function execution 10,000,000 times to get a more accurate measurement.Next, we will use
%timeit
to test the main loop of theasa
code calculation. For this, we must first import the relevant functions:In [2]: from asa import...