NumPy vs Python speed
Timing the same job with a list loop and with NumPy shows how much faster whole-array maths is.
In this page:
NumPy vs Python speed
Vectorized NumPy code pushes loops into optimized C, avoiding per-element Python overhead. On large data the speed-up is commonly 10x to 100x. You can measure it yourself with the time module.
Note:
Timing results vary by machine, so compare ratios rather than raw seconds.
Example: NumPy vs Python speed
import time
import numpy as np
n = 1_000_000
py_list = list(range(n))
arr = np.arange(n)
t0 = time.perf_counter()
py_sum = sum(x * 2 for x in py_list)
t_list = time.perf_counter() - t0
t0 = time.perf_counter()
np_sum = (arr * 2).sum()
t_np = time.perf_counter() - t0
print("Same answer:", py_sum == np_sum)
print("NumPy faster:", t_np < t_list)
# Output:
# Same answer: True
# NumPy faster: True
Related Topics
Common Mistakes
- Benchmarking tiny arrays where overhead dominates
- Timing the array creation instead of the operation
- Believing loops are always fine because they are simpler
Chapter Summary
- Vectorization removes Python loop overhead
- Speed-ups grow with data size
- Measure with time.perf_counter
- Avoid explicit loops on arrays
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: