Foundations to Frontier
Tests
C. Programming, Tools and HPC › C5 High-Performance Computing

Computer Architecture: CPU, Caches and the Memory Hierarchy

Modern processors can do arithmetic far faster than memory can feed them, so performance is mostly about data movement. This topic covers the CPU core (pipelines, superscalar and out-of-order execution, SIMD vector units, multiple cores), the memory hierarchy (registers, L1/L2/L3 caches, DRAM, with their latencies and bandwidths), how caches work (lines, sets, associativity, replacement, compulsory/capacity/conflict misses), locality, and what that means for code: loop order, contiguous layouts, blocking (tiling), avoiding power-of-two strides, and NUMA. In the exercises you build a set-associative cache simulator to measure row- versus column-major traversal and conflict misses, then compare loop orders and tile sizes for matrix multiplication by counting misses.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A fast cook with a far-away fridge

A modern processor is like a cook who can chop a hundred vegetables a second but whose fridge is down the hall. If the cook walks to the fridge for every single carrot, the speed is wasted. So the kitchen has a small counter right next to the cook (the cache): when you fetch one carrot, you bring the whole bag, hoping the next ones you need are in it. Programs are fast when they use things that are next to each other in memory, one after another.

Cache lines and loop order
traverse:
accesses 256
misses 256
miss rate 1.000
Thin outlines mark cache lines (8 doubles each). Row by row, the first access of each line misses and the next 7 hit: miss rate 1/8, whatever the cache size. Column by column, consecutive accesses touch different lines; with fewer than 16 lines in the cache, each line is evicted before the walk comes back to it, so every access misses. Tiling keeps the working set small enough to fit even when the full column doesn't.
Why engineers care

Simulation codes (orbit propagation, CFD, finite elements), image processing on satellites and neural-network kernels all live or die by memory access patterns. A loop reordering that costs nothing can make code ten times faster; on embedded flight processors with small caches the effect is even larger.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The cache is…
  2. 2. Why does reading memory in order help?
  3. 3. In the demo, why does walking by columns miss so often?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The hierarchy in numbers

Level Typical size Latency Notes
registers ~1 KB 0 cycles operands of instructions
L1 data cache 32–48 KB per core ~4 cycles (~1 ns) 64-byte lines
L2 1–2 MB per core ~12–15 cycles
L3 (shared) tens of MB ~40–60 cycles
DRAM GBs to TBs ~80–100 ns (~300 cycles) ~50–400 GB/s per socket
NVMe SSD TBs ~100 µs C4.3

A core may finish several floating-point operations per cycle (more with SIMD: AVX-512 processes 8 doubles at once), so one DRAM miss costs the time of hundreds of operations. Caches exploit temporal locality (reuse soon) and spatial locality (use neighbours).

📝 Quick check (Level 1)
0/3 answered
  1. 1. A cache line on x86 and most ARM CPUs is…
  2. 2. Roughly how many cycles is a DRAM access?
  3. 3. Reusing data you just used is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

How a cache works

Memory is cached in lines (64 B). An address splits into tag | set index | offset: the index selects a set, and a line can live in any of the set’s ways (associativity); within a full set the least recently used line is evicted. A 32 KiB, 8-way cache with 64 B lines has 32768/(64·8) = 64 sets: 6 offset bits and 6 index bits.

Misses come in three kinds: compulsory (first touch), capacity (the working set doesn’t fit), conflict (too many lines map to one set, even though the cache isn’t full). Power-of-two strides are the classic conflict trap: addresses 4096 bytes apart all map to the same set in the cache above, so 16 of them thrash an 8-way set.

Inside the core

Instructions are pipelined, several issue per cycle (superscalar), out of order when independent; branch predictors guess ahead. SIMD units apply one instruction to a vector of values; NumPy and compiled loops use them, Python loops do not. Multiple cores share L3 and memory bandwidth; on multi-socket machines memory is NUMA (faster from the local socket).

🐍 Exercise 1: a cache simulator
Implement a set-associative LRU cache (address split into tag, set and offset; hit and miss counting), replay row-major and column-major traversals of an n×n float64 matrix, compute average memory access time, and demonstrate conflict misses from a 4 KiB stride versus a padded stride.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Sets in a 1 MiB, 16-way cache with 64 B lines?
  2. 2. Misses because too many lines map to one set are…
  3. 3. A Python for-loop over a list of floats can't use…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Writing cache-friendly code

  • Traverse in storage order: NumPy and C arrays are row-major (C order), Fortran and MATLAB column-major; make the innermost loop run along the contiguous axis.
  • Structure of arrays (separate x, y, z arrays) streams better than an array of structures when a loop uses one field.
  • Blocking (tiling): restructure loops to work on sub-blocks that fit in cache, so each loaded line is reused many times. Optimized BLAS libraries tile for every cache level and use register blocking; that is why A @ B in NumPy reaches a large fraction of peak while a naive triple loop doesn’t.
  • Avoid power-of-two leading dimensions for arrays walked by columns (pad by one cache line).
  • Measure with hardware counters (perf stat -e cache-misses, VTune, likwid) rather than guessing.

Matrix multiplication as the case study

For C += A·B, the loop order changes the access pattern: with ikj the inner loop streams rows of B and C; with ijk it walks a column of B; with jki it walks columns of A and C. Tiling with T×T blocks reduces memory traffic from about n³ elements to about n³/T, as long as three T×T tiles fit in cache (3·T²·8 bytes ≤ cache size for doubles).

📝 Quick check (Level 3)
0/3 answered
  1. 1. Best inner-loop index for C order arrays in C += A B?
  2. 2. Largest square tile T such that three float64 tiles fit in 32 KiB?
  3. 3. Why is NumPy's matmul much faster than a triple loop in C?

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Caches, measured

Exercise 1. Summing a 256×256 float64 matrix through a 32 KiB 8-way cache: row-major misses once per line (miss rate 0.125, AMAT 13.5 cycles with a 100-cycle penalty), column-major misses on every access (1.0, AMAT 101 cycles) because 256 lines are touched before any is reused. A 32×32 matrix (8 KiB) fits entirely, so its column order costs nothing extra. Walking 16 addresses 4096 bytes apart thrashes one 8-way set (miss rate 1.00); padding the stride by one line (4160 B) spreads them over 16 sets (0.004).

Exercise 2: loop order and tiling for matrix multiplication. C += A·B for 48×48 float64 matrices (331 776 accesses), simulated through a 2 KiB 4-way cache with 64 B lines (compulsory misses: 864):

Variant Misses
ijk (column walk of B) 118 188
ikj (rows of B and C) 14 400
jki (columns of A and C) 223 488
tiled 4×4 / 6×6 / 8×8 / 12×12 / 16×16 / 24×24 9 672 / 12 272 / 5 094 / 7 948 / 11 085 / 14 976

Loop order alone changes misses 15×. The best tile, 8×8, is the largest whose three tiles fit (3·8²·8 = 1536 B ≤ 2048 B), and has 2.8× fewer misses than the best untiled order. The 6×6 tile is worse than 4×4: its 48-byte tile rows straddle 64-byte lines, so it drags in partial lines it doesn’t use. Tile sizes should be multiples of the line length.

🐍 Exercise 2 (research): loop order and tiling
Replay every load and store of C += A·B through a small set-associative cache for the loop orders ijk, ikj and jki and for tiled loops with several tile sizes; compare misses with the compulsory minimum, find the best tile and relate it to the cache capacity and line size.

Architecture in AI, robotics and aerospace

  • Scientific codes: stencil and finite-element kernels tiled for caches; structure-of-arrays particle layouts.
  • Onboard processors: radiation-tolerant CPUs (e.g. LEON, RAD750 class) have small caches and slow memory, so locality matters even more than on desktops.
  • Robotics: point-cloud processing and occupancy grids benefit from contiguous layouts and Morton (Z-order) indexing.
  • ML: every fast GPU and CPU kernel (GEMM, convolution, attention) is a carefully tiled loop nest (C5.2–C5.7).

References

  1. J. L. Hennessy, D. A. Patterson (2019). Computer Architecture: A Quantitative Approach, 6th ed. Morgan Kaufmann.
  2. U. Drepper (2007). “What every programmer should know about memory.” Red Hat (people.redhat.com/drepper/cpumemory.pdf).
  3. M. D. Hill, A. J. Smith (1989). “Evaluating associativity in CPU caches.” IEEE Transactions on Computers, 38(12).
  4. K. Goto, R. A. van de Geijn (2008). “Anatomy of high-performance matrix multiplication.” ACM TOMS, 34(3).
  5. M. S. Lam, E. E. Rothberg, M. E. Wolf (1991). “The cache performance and optimizations of blocked algorithms.” ASPLOS.