NumPy
We will illustrate now with an example how fast can be the computations using Nympy
We import first the built-in random
Python module and NumPy
:
import random
import numpy as np
We generate two Python lists, x
and y
, each one containing 1 million random
numbers between 0 and 1
n=1000000
x = [random.random() for _ in range(n)]
y = [random.random() for _ in range(n)]
x[:3], y[:3]
We compute now the element-wise average of all of these numbers: the average between the first element of x and the first element of y, and so on.
z = [(x[i] + y[i])/2 for i in range(n)]
How long does this computation take? It took for my computer ~ 165ms to make this computation
Let's now try to do the same using NumPy Library and compare the execution time.
We will first transform x
and y
into np.array
using NumPy
xa = np.array(x)
ya = np.array(y)
xa[:3], ya[:3]
za = (xa + ya)/2
Now it took for us only 24ms to make the same computation