Locality: Why Caches Work
Programs don't touch memory at random: they reuse what they just used and reach for its neighbors next. A cache bets on both habits, so a loop walking an array pays one slow miss per block and gets the rest of the block for free.
What the symbols mean
- Hit rate
The fraction of accesses whose data is already in the cache.
- Element size
Bytes per array element: 4 for an int, 8 for a double.
- Block size
Bytes the cache moves in one go, also called a cache line. Often 64.
What the symbols mean
- Number of elements
How many elements the loop reads.
- Block size
Bytes per block. Each block the array covers costs exactly one miss.
Explanation
A cache is simply a small, fast memory that sits right next to the processor and keeps copies of data it used recently, so the processor doesn't have to wait on the big, slow main memory every time. Locality is the reason that works. It's the habit real programs have of not touching memory at random. Temporal locality (temporal means "in time") says that what you used a moment ago, you'll probably use again soon. Spatial locality (spatial means "in space", here the space of addresses) says that when you use one address, you'll probably use its neighbors next. That's all a cache is betting on, and it wins the bet well over 90% of the time. The math in this lesson is mostly careful counting; bear with the vocabulary and it falls into place.
Where each kind comes from. Look at the most ordinary loop there is:
sum = 0
for i in 0 .. N-1:
sum = sum + a[i]
The variables and are touched on every pass: that's temporal locality. The elements sit side by side in memory and get read in that order: that's spatial locality. Even the loop's own instructions show both, since they run over and over and sit one after another.
Blocks: how a cache cashes in on spatial locality. A cache never fetches just the one byte you asked for. It moves memory in fixed chunks called blocks (or cache lines) of bytes, typically . So when the processor asks for and it isn't there, which is called a miss, the cache brings in the whole block around it, and for 4-byte ints through come along for the ride. The next 15 reads are hits: the data is already in the fast memory.
Counting the hit rate. The hit rate is the fraction of accesses that hit. A block of bytes holds elements of bytes each. Walking the array in order, the first element of each block misses and the other hit. So out of every accesses, exactly one misses:
For 4-byte ints and 64-byte blocks that's . Notice what isn't in the formula: the length . A longer array has more blocks, but every block plays out the same way, so the ratio doesn't move. On a first pass from an empty cache, the total number of misses is just the number of blocks the array covers, (assuming the array starts at the beginning of a block).
Stride. If the loop reads every -th element instead, the jump from one read to the next, called the stride, is bytes. Now only of each block's elements get used, so . Once the stride reaches the block size (), every read lands in a new block and the hit rate is . That's why walking a matrix down its columns can be painfully slow: a matrix is stored row by row, so the next element down a column is a whole row away.
Working sets: how a cache cashes in on temporal locality. The working set is the set of blocks a program is actively using over a short stretch of time. If the working set fits in the cache, the second time around everything hits. Loop times over an array that fits, and the misses all happen on the first pass, so . If it doesn't fit, the cache keeps throwing out blocks just before you come back for them, and the repetition buys you nothing.
There's an animation further down that walks a loop through an array, block by block.
A common mistake. It's tempting to think a bigger array means a worse hit rate, since there's more data to fetch. It isn't, for one pass in order: each block costs one miss and pays back hits, however many blocks there are. What a bigger array changes is whether it still fits in the cache for the next pass. That's a question about temporal locality, not spatial.
Another one. Counting misses per element instead of per block. A miss fetches a whole block, so the question to ask is always "how many different blocks does this code touch, and does it come back to them while they're still in the cache?"
Block sizes are powers of two for the same reason everything else in the machine is (see Binary and Hexadecimal), and that will matter when we see how a cache finds a block in Cache Organization. Next, in Hit Rate and Average Memory Access Time, we turn hit rates into time.
See it
Worked examples
A program adds up an array of doubles ( bytes each), in order, starting with an empty cache. The cache uses -byte blocks, and the array starts at the beginning of a block. How many misses are there, and what's the hit rate?
- 1
Start with a single block. It holds bytes and each double takes , so one block holds doubles.
Same array and cache, but now the loop reads only every th double: and so on. What's the hit rate? What if it reads every th double?
- 1
Find the stride, the jump in bytes from one read to the next. Each step skips ahead doubles of bytes: bytes.
Practice
Type your answer and check it. Solve them all to complete the lesson.
An array of 4-byte ints is read once, in order, through a cache with -byte blocks. What's the hit rate, as a decimal?
A loop reads four-byte ints in order, starting from an empty cache with -byte blocks. The array starts at a block boundary. How many misses are there?
Inside a loop, the variable is read and updated on every pass. Which kind of locality is that?
A loop reads every second element of an int array (4 bytes each): The cache has -byte blocks. What's the hit rate?
A photo filter processes a grayscale image, one byte per pixel, stored row by row. The cache has -byte blocks and is far too small to keep blocks around. Processing it row by row, each block misses once. Processing it column by column, every pixel is in a different block from the one before, and the block is gone by the time the next column comes back for it. How many times more misses does the column-by-column order cause?
An array of four-byte ints fits comfortably in the cache. A program loops over the whole array times, in order, starting from an empty cache with -byte blocks. What's the hit rate over all passes?
A program sums four-byte ints in order, through a cache with -byte blocks, starting cold. Each miss stalls the processor for clock cycles, and the clock runs at GHz. How many milliseconds does the program spend waiting on misses? (This uses CPU Time.)
The hardest one here. Get it, and you've got this lesson.
A matrix of 4-byte floats is stored row by row. A program sums it column by column (the inner loop goes down a column). The cache has -byte blocks, starts empty, can put any block anywhere, and when full throws out the least recently used block. How many misses are there in total (a) with a KiB cache ( blocks) and (b) with an KiB cache ( blocks)? Answer in that order.
Where it's used
Fast code is written around locality. Matrix libraries reorder their loops and work on small tiles that fit in the cache, so each block they fetch gets used many times before it's thrown out. Game engines often store "all the positions, then all the velocities" instead of one whole object at a time, so a loop that updates positions walks straight through memory. Analytics databases store each column together for the same reason. And it's why walking a linked list, whose nodes are scattered all over memory, can be many times slower than walking an array holding the same numbers: every node is a new block.