Cache memory, Explained | Introduction to Operating Systems

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 4.9 Free with a free account

Cache memory

Introduction to Operating Systems · Chapter 4: Memory ManagementSection 4.9 · lesson 33 of 838 min · free with a free account

← PagingNext lesson: Cache Coherence →

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

How CPU caches use locality, cache lines and mapping rules.

  • Explain cache hits, cache misses and the hit ratio
  • Distinguish temporal locality from spatial locality
  • Calculate average memory access time from hit time, miss rate and miss penalty
  • Compare direct-mapped, set-associative and fully associative caches

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,103 words). Read along, or search it.

Opening Analogy

Salt in Hand, Flour in the Storeroom

Sam, who runs a small online bakery, keeps the flour sack in the storeroom, a scoop of flour by the mixer, and a pinch of salt already in hand. Each place is smaller than the one before it, and much quicker to reach. Your computer plays the same game with data. And the winner is whoever guesses best what will be needed next.

Why Caches Exist

A CPU Faster Than RAM

A modern CPU works far faster than RAM can deliver its next piece of data. Without help, it would spend most of its time waiting. The fix is a cache: a small, very fast memory that keeps copies of the data most likely to be needed again. It's small, because fast memory costs far more per byte. And it's close, right inside or beside the CPU.

Hits and Misses

Checking the Cache First

When the CPU wants data, it checks the cache first. If the data is there, that's a cache hit, and the answer comes back at once. If not, it's a cache miss. The data is fetched from the slower level below, and a copy is kept in the cache for next time. The share of accesses that hit is the hit ratio. The higher it is, the less the CPU waits.

Cache Levels

L1, L2 and L3

Real CPUs use several levels of cache, each larger and slower than the last. They're called L1, L2 and L3. L1 is the smallest and fastest, and is usually private to each core. L2 is bigger, and L3, the biggest, is commonly shared by all the cores. Exact sizes differ from chip to chip. On this Mac, each fast core has 128 KiB of L1 data cache, and six fast cores share 16 MiB of L2. And this Mac's chip reports no L3 at all. So treat the levels as a pattern, not a rule.

Locality

Temporal and Spatial Locality

A cache would be useless if programs asked for random data. They don't. Programs show locality: a habit of staying close to what they used recently. Temporal locality: data used just now will probably be used again soon, like a loop counter touched on every turn. Spatial locality: data near what you just used will probably be needed next, like the next item of an array.

Cache Lines

Fetching Whole Blocks at Once

Caches use spatial locality by never fetching one lonely byte. They move a whole block, called a cache line. On most PCs, a line is sixty-four bytes. So reading one four-byte int is a miss, and it brings its fifteen neighbors along. The next fifteen reads are all hits. On this Mac, a cache line is a hundred twenty-eight bytes, so one miss brings thirty-one neighbors.

Average Access Time

Hit Time Plus Miss Rate Times Penalty

Does caching really pay? The average access time is the hit time, plus the miss rate times the miss penalty. Take illustrative numbers. L1 takes one nanosecond and hits ninety-five percent of the time. RAM takes one hundred nanoseconds. So the average is one, plus point zero five times one hundred: six nanoseconds. Five of those six come from the misses. Now add an L2 that takes four nanoseconds, and catches eighty percent of what L1 misses. A miss now costs four, plus point two times one hundred: twenty-four. The average falls to two point two nanoseconds, against one hundred with no cache.

Quick Check

A Two-Nanosecond Cache at 90 Percent

Quick check. A different cache takes two nanoseconds per hit, and hits ninety percent of the time. A miss costs fifty nanoseconds more. What's the average access time? Five nanoseconds? Seven? Or forty-seven? Pause, and decide. Seven nanoseconds. Every access pays the two nanosecond hit time. The misses, one in ten, add a tenth of fifty, which is five. Two plus five is seven. Five forgets the hit time. And forty-seven multiplies by the hit rate, when the miss rate is what counts.

Mapping Rules

Direct Mapped, Set and Fully Associative

A cache has far fewer slots than RAM has blocks, so a rule must say which slot a block may use. Direct mapped: each block has exactly one slot, its block number modulo the number of slots. Simple and fast. But with four slots, blocks zero, four and eight all want slot zero. They keep throwing each other out, while slots two and three sit empty. Fully associative: a block may go in any slot. Flexible, but every slot must be checked. Set associative is the middle road. A block maps to one small set of slots, such as four, and may use any slot in that set.

Simulation

Walking a Table by Rows and Columns

A small simulator makes this concrete. Its cache holds sixty-four lines of sixty-four bytes, and it reads a sixty-four by sixty-four table of four-byte ints. The table sits in memory one row after another. Walking by rows reads neighbors in order: one miss per line, then fifteen hits. That gives three thousand eight hundred forty hits out of four thousand ninety-six reads, on every kind of cache. Walking by columns jumps two hundred fifty-six bytes each step. Direct mapped gets zero hits, and four-way set associative also gets zero. Only the fully associative cache, which can hold all sixty-four lines at once, gets the three thousand eight hundred forty hits back.

Common Mistake

Caches Help Only Reuse and Neighbors

Why did the columns fail? A column touches sixty-four different lines before it comes back to the first one. In the direct-mapped cache, those sixty-four lines pile into just sixteen slots, and keep evicting each other. So a cache doesn't make every program faster. It helps only programs that reuse data, or read their neighbors.

Quick Check

Which Block Evicts Block Three

Quick check. A direct-mapped cache has eight slots. A loop keeps reading block three and one other block, over and over. Which block will keep throwing block three out? Block eleven? Block four? Or block eight? Pause, and decide. Block eleven. Eleven modulo eight is three, so blocks three and eleven both map to slot three, and each one evicts the other. Block four goes to slot four, and block eight goes to slot zero, so those pairs can sit side by side. Neighbors don't clash. Blocks clash when their numbers differ by a multiple of the slot count.

Real Case

Sam's Kitchen as a Cache

Back to Sam's kitchen. The pinch of salt in hand is like L1, the scoop by the mixer is like L2, and the storeroom is RAM. Sam keeps close whatever the next batch will need. A good cache does the same, by betting on locality.

Key Takeaways

Copies Close to the CPU

To recap. A cache keeps copies of likely data close to the CPU. A hit is fast, and a miss goes to the slower level. Caches work because of temporal and spatial locality, and they move whole cache lines. Average access time is the hit time, plus the miss rate times the miss penalty. And the mapping rule, direct mapped, set associative or fully associative, decides which slot a block may use.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Cache memory

What is the difference between temporal and spatial locality?
Temporal locality means data used just now will probably be used again soon, like a loop counter touched on every turn. Spatial locality means data near what was just used will probably be needed next, like the following element of an array. Caches exploit temporal locality by keeping recent data, and spatial locality by fetching a whole cache line, often 64 bytes, at once.
How do you calculate average memory access time?
Average memory access time equals the hit time plus the miss rate times the miss penalty. For a cache that takes 2 nanoseconds per hit, hits 90 percent of the time, and adds 50 nanoseconds per miss, the average is 2 plus 0.1 times 50, or 7 nanoseconds. A common slip is multiplying the penalty by the hit rate instead of the miss rate.
What is the difference between a direct-mapped and a set-associative cache?
In a direct-mapped cache, each memory block can go in exactly one slot, its block number modulo the number of slots. In a set-associative cache, a block maps to one small set, such as four slots, and may use any slot in that set. Direct mapping is simple and fast but suffers more conflicts, and a fully associative cache lets a block use any slot.
Why can looping over a 2D array by columns be slower than by rows?
Walking an array stored row by row in column order can be slower because each step jumps to a different cache line, so spatial locality is lost. In one simulation of a 64 by 64 table of 4-byte ints, row order gave 3,840 hits in 4,096 reads, while column order gave zero hits on direct-mapped and four-way caches, because the column's 64 lines kept evicting each other.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Operating Systems.

83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →