Speed Comparisons: NumPy vs Pure Python

Speed comparisons for two different routines.

First, some imports:


In [1]:
import numpy as np
import random

Fix data size


In [2]:
n = int(10**6)

Make an evenly spaced grid of n points between 0 and 1.


In [7]:
%%timeit
x = []
a = 0
step = 1 / (n - 1)
for i in range(n):
    x.append(a)
    a += step


10 loops, best of 3: 117 ms per loop

Do the same using np.linspace.


In [8]:
%%timeit
x = np.linspace(0, 1, n)


100 loops, best of 3: 3.92 ms per loop

Take the maximum of n standard normals.


In [5]:
%%timeit
running_max = 0
for i in range(n):
    x = random.normalvariate(0, 1)
    if x > running_max:
        running_max = x


1 loop, best of 3: 1 s per loop

Do the same in NumPy.


In [6]:
%%timeit
all_max = np.max(np.random.randn(n))


10 loops, best of 3: 38.4 ms per loop

In [ ]: