Transcript
Adding two numbers takes your processor a fraction of a nanosecond. Getting one number from main memory takes about a hundred nanoseconds. That's hundreds of ticks of waiting, for every single number. And yet your computer doesn't feel hundreds of times slower. The reason is a cache. Today, we see how it works.
A cache is a small, fast memory right inside the processor, built from the SRAM cells we saw in episode eight. It keeps copies of data the processor used recently. When the processor asks for an address, the cache checks first. If it's there, that's a hit: an answer in a few ticks. If it isn't, that's a miss. The data comes from main memory, slowly, and the cache keeps a copy for next time.
Why would the same data be needed again? Because programs are predictable. A loop uses the same few variables over and over. And when a program reads one address, it usually reads the next ones soon after, like walking through a list. So on a miss, the cache doesn't fetch just one number. It fetches a whole block, typically sixty-four bytes, called a cache line. Watch a loop add up sixteen numbers. Blocks of four: the first read of each block misses, the next three hit. Twelve hits out of sixteen. Run the loop again, and everything is already there. Sixteen out of sixteen.
But the cache is tiny. Where does each block go? The simplest rule: divide the block number by the number of lines, and the remainder picks the line. Block thirteen goes to line five, because thirteen divided by eight leaves five. Simple, but two busy blocks can fight over the same line, and keep kicking each other out. So most caches let each block sit in one of a few lines: two, four, or more. That's called set-associative.
When those lines are full, which one goes? Usually the one that hasn't been used for the longest time: least recently used.
And writing? Instead of updating slow memory every time, the cache can just mark its copy as changed, or dirty. Only when that line is kicked out does it get written back to memory. That's called write-back, and it saves a lot of slow trips.
Real processors stack several caches: a tiny level-one cache in each core, a bigger level two, and a large shared level three. Each level is bigger and slower than the one before, but all of them are much faster than main memory. Most of the time, the data is found in level one. So memory feels fast, even though it isn't.
So: keep recently used data close, fetch whole lines, pick lines by address, evict the least recently used, and write back later. But caches aren't the only trick memory plays. Every program believes it has the whole memory to itself. Next time: virtual memory. See you there.
Next episode: virtual memory. Why every program thinks the memory is all its own.