Measuring execution time
In order to take decisions on code optimization, one often has to compare several code alternatives and decide which code should be preferred based on the execution time. Furthermore, discussing execution time is an issue when comparing different algorithms. In this section, we present a simple and easy way to measure execution time.
Timing with a magic function
The easiest way to measure the execution time of a single statement is to use IPython’s magic function %timeit
.
Note
The shell IPython adds additional functionality to standard Python. These extra functions are called magic functions.
As the execution time of a single statement can be extremely short, the statement is placed in a loop and executed several times. By taking the minimum measured time, one makes sure that other tasks running on the computer do not influence the measured result too much. Let's consider four alternative ways to extract nonzero elements from an array as follows:
A=zeros(...