Lite / Independent Engineering Research / 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?
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.
Predict
A cache with 16-byte blocks reads 32 consecutive 4-byte integers, starting empty. How many misses?
- 32
- 8
- 1
- 16
Guess first, then reveal
Each miss brings in a 16-byte block holding 4 integers, so only every fourth access misses: 32/4 = 8. That is spatial locality at work.
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.
What the interactive shows (text version)
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.
Watch (optional)
Watch for: 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.
“Memory & Storage: Crash Course Computer Science #19” by CrashCourse (opens YouTube; streaming video uses a lot of data)
The video is optional. Everything you need is in this lesson's text.
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
Intuitive
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).
Technical
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.
Mathematical
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.
Applied
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.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
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.
Reflect
Which piece of your own code would you now rewrite for locality?
Write your answer on paper or in your own notes. Lite never stores what you write.