Sub topic 16
Performance Tips and Common Pitfalls
This chapter assumes you know how to create arrays, slice them, tell views from copies, and use broadcasting and axis reductions. It also assumes you have met strides. Here you will pull those ideas together into habits that make NumPy code fast and correct. Most NumPy bugs and slowdowns come from a few causes: Python-level loops, unplanned copies, wrong dtypes, and broadcasting that succeeds when it should have failed.
Where the speed comes from
An ndarray stores typed values in one contiguous block of memory. A universal function (ufunc) such as np.add runs a compiled loop over that block. It skips the per-element type checks and object handling that a Python loop pays for.
That gives you a rule: keep the work inside NumPy calls. Every trip back into the Python interpreter for a single element costs far more than the arithmetic itself.
Replace element loops with array expressions
Iterating over an ndarray in Python is slower than iterating over a list. Each step creates a NumPy scalar object. Compare a loop with a single call that computes the same sum of squares.
import time
import numpy as np
x = np.random.default_rng(0).random(1_000_000)
t0 = time.perf_counter()
total = 0.0
for v in x:
total += v * v
loop_time = time.perf_counter() - t0
t0 = time.perf_counter()
total_vec = float(x @ x)
vec_time = time.perf_counter() - t0
print(np.isclose(total, total_vec)) # True
print(f"loop {loop_time:.3f}s, vectorized {vec_time:.5f}s")The exact times depend on your machine, but the vectorized version is typically faster by two orders of magnitude or more. The results are compared with np.isclose because the two versions add the numbers in a different order, so the last digits can differ.
Cut down on temporaries
An expression like a * b + c allocates a full-size temporary array for a * b, then another for the sum. On large arrays the allocation and memory traffic often cost more than the arithmetic. You can reuse memory in two ways.
- Use in-place operators:
a += b,a *= 2. - Pass
out=to a ufunc to say where the result goes.
import numpy as np
a = np.ones(5)
b = np.full(5, 2.0)
c = np.full(5, 0.5)
tmp = np.empty_like(a)
np.multiply(a, b, out=tmp) # tmp = a * b, no new allocation
tmp += c # in place
print(tmp) # [2.5 2.5 2.5 2.5 2.5]For small arrays this is not worth the extra code. Apply it where profiling shows memory pressure.
The same logic applies to growing results. np.append and np.concatenate copy the whole array every call, so building an array in a loop is quadratic in total work. Preallocate with np.empty(n) and assign into it, or collect values in a Python list and convert once with np.array(values).
Memory layout and contiguity
Default arrays are C-contiguous: the last axis changes fastest in memory. Reading along the last axis walks adjacent memory, which the CPU cache handles well. Reading along the first axis jumps by a full row each step.
A transpose swaps strides without moving data, so a.T is usually not contiguous. Most operations still work on it, but they may run more slowly. If you will use a transposed array many times, you can pay for one copy up front.
import numpy as np
a = np.arange(12).reshape(3, 4)
t = a.T
print(t.flags['C_CONTIGUOUS']) # False
c = np.ascontiguousarray(t)
print(c.flags['C_CONTIGUOUS']) # True
print(np.shares_memory(t, c)) # False, c owns new dataMeasure with time.perf_counter or IPython's %timeit before and after. The copy only pays off when the array is reused enough.
Dtype choice also matters. A float64 array uses 8 bytes per element and a float32 array uses 4. If your data does not need double precision, float32 halves memory use and memory bandwidth. Check the footprint with a.nbytes.
Pitfalls that give wrong answers
Views change the original
A basic slice is a view, so assigning into it writes to the source array. Call .copy() when you need independence. Use np.shares_memory(a, b) to check whether two arrays overlap in memory.
Fancy and boolean indexing return copies, which reverses the behavior.
import numpy as np
a = np.arange(5)
print(np.shares_memory(a, a[1:3])) # True, basic slice
print(np.shares_memory(a, a[[1, 2]])) # False, fancy indexing
b = np.arange(6).reshape(2, 3)
print(np.shares_memory(b, b.reshape(3, 2))) # True
print(np.shares_memory(b, b.T.reshape(6))) # FalseThe last line shows that reshape returns a view only when the existing strides allow it. Otherwise it silently copies. Never write code that depends on a reshaped array writing through to the original unless you have checked.
Integer overflow wraps silently
Fixed-width integers do not grow. Array arithmetic that exceeds the range wraps around with no error.
import numpy as np
a = np.array([100, 120], dtype=np.int8)
print(a + 100) # [-56 -36], wrapped around
print(a.astype(np.int64) + 100) # [200 220]Choose a dtype wide enough for the largest intermediate value, not only for the stored data. Summing a large uint8 image, for example, needs a wider accumulator.
In-place operations cannot change dtype
In-place operators keep the left array's dtype. Adding a float to an integer array in place raises an error rather than converting.
import numpy as np
a = np.arange(3)
try:
a += 0.5
except TypeError as e: # numpy's UFuncTypeError is a TypeError subclass
print("error:", type(e).__name__)
a = a + 0.5 # creates a new float64 array
print(a) # [0.5 1.5 2.5]Assigning floats into an integer array by index (a[0] = 2.7) is different. It truncates without any error.
Broadcasting that works by accident
Broadcasting never complains when shapes are compatible, even if you did not mean to combine them that way. A common case is a (3,) array and a (3, 1) array.
import numpy as np
pred = np.array([1.0, 2.0, 3.0]) # shape (3,)
target = np.array([[1.0], [2.0], [3.0]]) # shape (3, 1)
diff = pred - target
print(diff.shape) # (3, 3), not (3,)
print(np.mean(diff ** 2)) # wrong error value, averaged over 9 pairs
print(np.mean((pred - target.ravel()) ** 2)) # 0.0Print .shape of intermediate results when a number looks off. Use ravel() or reshape to make shapes match deliberately.
Floating point and NaN
Floats are approximate and NaN is never equal to anything, including itself.
import numpy as np
print(0.1 + 0.2 == 0.3) # False
print(np.isclose(0.1 + 0.2, 0.3)) # True
print(np.nan == np.nan) # False
v = np.array([1.0, np.nan, 3.0])
print(v.mean()) # nan
print(np.nanmean(v)) # 2.0Compare floats with np.isclose or np.allclose, test for missing values with np.isnan, and use the nan-prefixed reductions when NaN should be ignored.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Loop over array is very slow | One Python step per element | Use ufuncs, masks, or axis reductions |
| Memory spikes in long expressions | Full-size temporaries | `out=` and in-place operators |
| Building an array in a loop is slow | `np.append` copies each time | Preallocate or collect in a list |
| Original data changed unexpectedly | Slice is a view | `.copy()` |
| Edit to a result did not reach the source | Fancy or boolean indexing copies | Assign through the index on the source |
| Totals look wrapped or negative | Integer overflow | Wider dtype |
| Result shape is `(n, n)` | Accidental broadcasting | Check shapes, `ravel()` or `reshape` |
Exercise
A function builds result = np.array([]) and calls result = np.append(result, f(i)) for 100,000 values of i. Why is this slow, and how would you fix it if f returns a float and cannot be vectorized?
Show answer
Each np.append allocates a new array and copies all existing elements, so the total work grows quadratically with the number of values. Preallocate with result = np.empty(100_000) and assign result[i] = f(i), or collect the values in a Python list and call np.array(values) once at the end. If f can be rewritten with array operations, vectorizing removes the loop entirely.
Exercise
a = np.arange(6).reshape(2, 3). You write flat = a.T.reshape(6) and then set flat[0] = 100. Does a change? How would you confirm your answer in code?
Show answer
No. The transpose is not C-contiguous, so reshape(6) cannot be done as a view and returns a copy. Confirm with np.shares_memory(a, flat), which returns False, or by printing a after the assignment and seeing it unchanged.