School/✦ Research Engineer/Week 21
Locality and the memory hierarchy
Two loops add up the same million numbers. One is ten times slower. Same chip, same maths. What is different?
About 40 min · 3 goals · Checked by automated tests
1.Why should I care?
A modern core can do an addition in under a nanosecond but waits around a hundred nanoseconds for main memory. Caches hide that gap, but only for programs with locality. Writing cache-friendly code is often the cheapest speed-up an engineer can get.
- ◇ Order registers, caches, main memory and storage by latency, capacity and cost per byte.
- ◇ Explain temporal and spatial locality with code examples.
- ◇ Predict qualitatively whether an access pattern will hit or miss in a cache.
2.Discover
Run 'Walk an array', then 'Small loop, twice', then 'Big stride', all direct-mapped with 16 B blocks. For each, predict the hit rate before you press Show all. Then try 32 B blocks on the array walk and on the stride.
Loading the interactive…
Can't use the interactive? Read a description instead
The cache simulator lists each address, its set and tag, and whether it hits. With 16-byte blocks: walking 32 integers gives 8 misses and 24 hits; reading 16 integers twice gives 4 misses; a 64-byte stride misses every time.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1
A filter applies the same 5 coefficients to every sample. Which locality do the coefficients show?
4.Predict
A cache with 16-byte blocks reads 32 consecutive 4-byte integers, starting empty. How many misses?
Guess first. Being wrong here is how the surprise works.
5.Understand
The hierarchy
Registers (bytes to a few KB, under a nanosecond), L1 cache (tens of KB, about 1 ns), L2/L3 (hundreds of KB to tens of MB, several to tens of ns), DRAM (GB, around 100 ns), flash or disk (TB, microseconds to milliseconds). Each level is bigger, slower and cheaper per byte than the one above. Typical figures vary widely between chips.
Temporal locality
Data used now is likely to be used again soon: loop counters, a filter's coefficients, the top of the stack. Keeping recently used data in a small fast memory serves those repeat visits.
Spatial locality
Data near what you just used is likely to be used next: the next array element, the next instruction. Caches move whole blocks (often 64 bytes) so one miss pre-loads the neighbours. Walking a 2-D array row by row in a row-major language uses this; walking it column by column wastes it.
Explain it another way
Your desk, your bookshelf and the library. You keep the book you're using on the desk (temporal) and take the next chapter's book from the same shelf while you're there (spatial).
Hit rate h = hits/accesses. Misses are compulsory (first touch), capacity (working set too big) or conflict (blocks fighting for the same set). Block size trades spatial-locality gains against fewer blocks and a longer miss penalty.
For a sequential walk of 4-byte words with B-byte blocks, the miss rate is 4/B: 25% at 16 B, 6.25% at 64 B. For a stride s ≥ B, every access misses: miss rate 1.
Image-processing code tiles an image into small squares that fit in the cache, processing each completely before moving on. The arithmetic is identical; the speed is not.
Worked example 1
A C program sums a 1000×1000 int matrix as sum += a[j][i] (column by column). Why is it slow, and what is the fix?
C stores rows contiguously, so a[j][i] then a[j+1][i] are 4000 bytes apart: every access touches a new block. Swap the loops to a[i][j] so consecutive accesses share blocks; the miss rate drops from about 100% to about 4/64 ≈ 6%.
Common mix-ups
- Memory access time is constant, so only operation counts matter.
✓ A cache miss can cost 100 times a hit. Access patterns change real run time massively. - Bigger blocks are always better.
✓ They help sequential access but waste bandwidth and capacity on strided or random access.
6.Watch
→ Notice how each memory technology trades speed for capacity: that trade is why a hierarchy exists.
A history of memory technologies that makes the speed-versus-capacity trade-off of the hierarchy concrete.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
A loop reads 256 consecutive 4-byte floats into an empty cache with 64-byte blocks. How many misses?
Practice 3 · a fresh version every time
A direct-mapped cache has 4 lines of 16 bytes and starts empty. The CPU reads these byte addresses in order: 124, 272, 272, 368, 20, 20, 272, 144, 144, 144. How many reads hit?
Practice 4
Reading every 64th byte with 16-byte blocks gives 100% misses. What happens if blocks grow to 32 bytes?
Practice 5
Which list is ordered from fastest to slowest?
8.Apply it
Write two versions of a 2-D image blur in the Code Lab: row-major and column-major traversal. Without timing them, predict which is faster and by roughly how much using a 64-byte block. Then explain how you would test your prediction fairly.
9.Reflect
Concepts: Memory hierarchy and caches · Lists, dictionaries and tabular data