TExcelTAD
Home › NumPy › Performance and Vectorization

Performance and Vectorization

NumPy is fast when you let it work on whole arrays and slow when you push elements through a Python loop one by one. Rewriting loops as array expressions is called vectorization, and it is the single most important skill for writing good NumPy code.

Measuring the difference

Let's compute the squared distance of a million points from the origin, first with a loop, then vectorised. We print only rounded speed-ups, since exact times depend on your device:

python · try it yourself
import numpy as np
import time

rng = np.random.default_rng(0)
x = rng.random(1_000_000)
y = rng.random(1_000_000)

t0 = time.perf_counter()
loop = np.empty_like(x)
for i in range(len(x)):
    loop[i] = x[i] ** 2 + y[i] ** 2
t_loop = time.perf_counter() - t0

t0 = time.perf_counter()
vec = x ** 2 + y ** 2
t_vec = time.perf_counter() - t0

print("same results:", np.allclose(loop, vec))
print("vectorised at least 20x faster:", t_loop > 20 * t_vec)
same results: True
vectorised at least 20x faster: True

On a typical computer the difference is a factor of 100 or more. The loop pays for interpreting Python, creating a float object and doing a type check for every single element; the vectorised version runs a tight compiled loop.

Recipes: from loops to array code

Loop pattern Vectorised version
apply a formula to each element write the formula on arrays: a * 2 + 1
if / else per element np.where(cond, x, y) or np.select
count / sum matching elements (cond).sum(), a[cond].sum()
running total np.cumsum
compare each element with the previous np.diff, or slices a[1:] vs a[:-1]
all pairs of two lists broadcasting a[:, None] - b
look up values by index fancy indexing table[idx]
count categories np.bincount, np.unique(..., return_counts=True)

Here is a loop with an if, and its vectorised twin:

python · try it yourself
import numpy as np

kwh = np.array([120, 340, 80, 510, 260])

# Loop version: 0.20 per kWh up to 200, then 0.35 for the rest
bills = []
for k in kwh:
    if k <= 200:
        bills.append(k * 0.20)
    else:
        bills.append(200 * 0.20 + (k - 200) * 0.35)
print(np.round(bills, 2))

# Vectorised version
vec = np.where(kwh <= 200, kwh * 0.20, 200 * 0.20 + (kwh - 200) * 0.35)
print(vec.round(2))

# Even simpler: the tiered formula with clip
print((np.minimum(kwh, 200) * 0.20 + np.clip(kwh - 200, 0, None) * 0.35).round(2))
[ 24.   89.   16.  148.5  61. ]
[ 24.   89.   16.  148.5  61. ]
[ 24.   89.   16.  148.5  61. ]

Comparing neighbours with slices

Many "loop over i and look at i−1" problems become slice arithmetic:

python · try it yourself
import numpy as np

temps = np.array([12, 14, 13, 17, 19, 18, 21])
rising = temps[1:] > temps[:-1]                       # compare each day with the previous
print(rising)
print("days warmer than the day before:", rising.sum())

# 3-day moving average without a loop
window = 3
moving = np.convolve(temps, np.ones(window) / window, mode="valid")
print(moving.round(2))
[ True False  True  True False  True]
days warmer than the day before: 4
[13.   14.67 16.33 18.   19.33]

Avoid growing arrays

np.append and np.concatenate copy the whole array every time. Inside a loop that makes the work quadratic. Allocate once, then fill, or build a Python list and convert at the end:

python · try it yourself
import numpy as np

n = 5
# Slow pattern (fine for 5 items, terrible for 100,000):
slow = np.array([])
for i in range(n):
    slow = np.append(slow, i ** 2)

# Better: preallocate and fill
fast = np.empty(n)
for i in range(n):
    fast[i] = i ** 2

# Best: no loop at all
best = np.arange(n) ** 2
print(slow, fast, best)
[ 0.  1.  4.  9. 16.] [ 0.  1.  4.  9. 16.] [ 0  1  4  9 16]

Other performance tips

  • Pick the right dtype. float32 halves memory compared with float64, which also speeds up memory-bound operations, if the precision is enough.
  • Use in-place operations for big arrays: a *= 2 or np.multiply(a, 2, out=a) avoid creating a temporary array.
  • Prefer views to copies. Slicing is free; fancy indexing copies.
  • Use built-in reductions (sum, mean, max) instead of Python's sum() / max() on arrays.
  • Know when to stop. If a computation is inherently sequential (each step depends on the last in a non-trivial way), a loop may be the honest solution; tools like Numba or Cython can compile such loops.
python · try it yourself
import numpy as np

a = np.arange(1_000_000, dtype=np.float64)
print(a.nbytes // 1_000_000, "MB as float64")
print(a.astype(np.float32).nbytes // 1_000_000, "MB as float32")

b = a.copy()
np.multiply(b, 2, out=b)          # in place, no temporary array
print(b[:5])
8 MB as float64
4 MB as float32
[0. 2. 4. 6. 8.]

Test yourself

Which is the vectorised replacement for an if/else applied to every element?

  1. A list comprehension
  2. np.where(cond, x, y)
  3. np.vectorize
  4. A while loop

Why is calling np.append inside a long loop slow?

  1. It sorts the array
  2. It copies the entire array on every call
  3. It converts to a list
  4. It is not slow

How can you compare each element of a with its predecessor without a loop?

  1. a > a
  2. a[1:] > a[:-1]
  3. a[::-1] > a
  4. np.sort(a)