Loading Python for AI Engineering...
NumPy and PyTorch tensors allocate single contiguous blocks of memory where elements sit adjacent to each other. Unlike Python pointer lists, contiguous memory fits into CPU L1/L2 cache lines and enables single-instruction multiple-data (SIMD) vector processing.
“A contiguous array is a roll of pennies where every coin is touching. A Python list is a box of scavenger hunt clues, each pointing to a coin hidden in a different room.”
Using Python for-loops to iterate over arrays element-by-element, throwing away 100x hardware vector speedups.
import numpy as np
# Contiguous block: exactly 4,000,000 bytes in memory
arr = np.ones(1_000_000, dtype=np.float32)
print("Flags:", arr.flags['C_CONTIGUOUS']) # True
print("Itemsize:", arr.itemsize) # 4 bytes
print("Total bytes:", arr.nbytes) # 4,000,000 bytes