Skip to content
Chethan Yadav_
Computer Architecture

COA/Lesson 5 of 6/8 min read

Memory Hierarchy and Cache

The memory hierarchy, locality, cache mapping (direct, fully and set associative), replacement and write policies, AMAT and cache coherence.


On this page

Memory Hierarchy

Fast memory is expensive and small; cheap memory is slow and large. The hierarchy combines them so the system looks almost as fast as the top and almost as big as the bottom.

LevelTypical sizeTypical latencyTechnology
RegistersUnder 1 KBUnder 1 ns (0 cycles)Flip-flops
L1 cache32 to 64 KB per coreAbout 1 ns (4 cycles)SRAM
L2 cache256 KB to 2 MB per coreAbout 4 ns (12 cycles)SRAM
L3 cache8 to 64 MB sharedAbout 10 to 20 nsSRAM
Main memory8 to 128 GBAbout 60 to 100 nsDRAM
SSDTBsAbout 100 usFlash
HDDTBsAbout 5 to 10 msMagnetic

Moving down: larger, cheaper per byte, slower. Each level caches the level below it.

SRAM

Static RAM stores each bit in a 6-transistor flip-flop. Fast, no refresh needed, but large and expensive. Used for caches and registers.

DRAM

Dynamic RAM stores each bit as charge in a capacitor with one transistor. Dense and cheap, but the charge leaks, so it must be refreshed every few milliseconds, and reads are slower. Used for main memory.

SRAMDRAM
Cell6 transistors1 transistor + capacitor
SpeedFastSlower
RefreshNoYes
Density and costLow density, expensiveHigh density, cheap
UseCacheMain memory

Locality of Reference

Caches work because programs do not access memory randomly.

  • Temporal locality: recently used data is likely to be used again soon (loop counters, hot variables).
  • Spatial locality: data near recently used data is likely to be used soon (array traversal, sequential instructions).
// Good spatial locality: row-major traversal of a C array
for (i = 0; i < N; i++)
    for (j = 0; j < N; j++)
        sum += a[i][j];
 
// Poor: column-major traversal jumps N * 4 bytes each access
for (j = 0; j < N; j++)
    for (i = 0; i < N; i++)
        sum += a[i][j];

The second loop can be several times slower for large N purely because of cache misses.

Cache Memory

A small, fast SRAM between the CPU and main memory that holds copies of recently used blocks.

Cache Hit

The requested data is in the cache. A miss means it must be fetched from the next level.

Hit rate  = hits / total accesses
Miss rate = 1 - hit rate

The three Cs of misses

Miss typeCauseReduce with
Compulsory (cold)First access to a blockLarger blocks, prefetching
CapacityCache too small for the working setBigger cache
ConflictToo many blocks map to the same setHigher associativity

A fourth C for multiprocessors: coherence misses.

Cache Line

The unit of transfer between cache and memory, also called a block, typically 64 bytes. On a miss, the whole line is loaded, which is how spatial locality is exploited.

A memory address is split into fields:

| Tag | Index | Block offset |
  • Block offset: byte within the line; log2(line size) bits.
  • Index: which set; log2(number of sets) bits.
  • Tag: remaining high bits; identifies which memory block is stored.

Each line also stores a valid bit and, for write-back caches, a dirty bit.

Cache mapping

Direct Mapping

Each memory block maps to exactly one cache line: line = block number mod number of lines.

  • Simple, fast, cheap (one tag comparison).
  • Suffers conflict misses when two hot blocks map to the same line and keep evicting each other (thrashing between them).

Fully Associative

A block can go in any line. Every tag must be compared in parallel. No conflict misses, but expensive hardware; used only for small caches.

Set Associative

The cache is divided into sets of k lines (k-way). A block maps to one set and can occupy any line within it. The practical compromise: L1 caches are often 8-way, L3 12 to 16-way.

MappingPlacementComparatorsConflict misses
Direct mappedOne line1Most
k-way set associativeAny of k lines in one setkFewer
Fully associativeAny lineAll linesNone

Direct mapped is 1-way set associative; fully associative is a single set.

Worked example

32 KB cache, 64-byte lines, 4-way set associative, 32-bit addresses.

Lines  = 32 KB / 64 B = 512
Sets   = 512 / 4 = 128
Offset = log2(64)  = 6 bits
Index  = log2(128) = 7 bits
Tag    = 32 - 7 - 6 = 19 bits

Cache Replacement Policy

On a miss in a full set, which line to evict?

PolicyIdeaNotes
LRUEvict least recently usedGood, expensive for high associativity
Pseudo-LRUTree bits approximate LRUCommon in hardware
FIFOEvict oldest loadedSimple, ignores use
RandomPick randomlyCheap, surprisingly decent
Optimal (Belady)Evict the one used furthest in futureTheoretical benchmark only

Write policies

Write-Through

Every write updates both the cache and main memory. Simple and memory is always up to date, but generates heavy memory traffic. Usually paired with a write buffer.

Write-Back

Writes update only the cache and set the dirty bit. The line is written to memory only when evicted. Less traffic, faster, but more complex and memory can be stale.

On a write miss:

  • Write-allocate: load the line into the cache, then write (pairs with write-back).
  • No-write-allocate: write directly to memory (pairs with write-through).

AMAT

Average Memory Access Time:

AMAT = Hit time + Miss rate * Miss penalty

Example: hit time 1 ns, miss rate 5%, miss penalty 100 ns. AMAT = 1 + 0.05 * 100 = 6 ns.

Multi-level:

AMAT = HitL1 + MissL1 * (HitL2 + MissL2 * PenaltyL2)

With L1 1 ns and 5% miss, L2 10 ns and 20% local miss, memory 100 ns: 1 + 0.05 * (10 + 0.2 * 100) = 2.5 ns. Adding L2 more than halves AMAT.

Ways to improve: lower hit time (small, simple L1), lower miss rate (bigger, more associative, prefetching), lower miss penalty (multi-level caches, critical word first).

Cache Coherence

In a multicore CPU, each core has its own L1 and L2. If two cores cache the same address and one writes, the other's copy becomes stale. Coherence protocols keep copies consistent.

  • Snooping: caches watch (snoop) a shared bus for writes. Works for a small number of cores.
  • Directory-based: a directory tracks which caches hold each line. Scales to many cores.

MESI

The common snooping protocol. Each cache line is in one of four states:

StateMeaning
ModifiedOnly this cache has it; dirty
ExclusiveOnly this cache has it; clean
SharedSeveral caches may have it; clean
InvalidNot valid

A write to a Shared line broadcasts an invalidate so other copies become Invalid.

False sharing: two threads write different variables that happen to sit on the same cache line. The line ping-pongs between cores and performance collapses. Fix: pad or align hot per-thread data to separate 64-byte lines.

For how the OS layers virtual addresses on top of this, see virtual memory.

Quick revision

  • Hierarchy: registers, L1, L2, L3 (SRAM), DRAM, SSD, HDD; faster and smaller at the top.
  • Temporal and spatial locality make caches effective; traverse arrays in memory order.
  • Address = tag, index, offset; 64-byte lines are typical.
  • Direct mapped: one place, conflict misses. Fully associative: anywhere, expensive. Set associative: compromise.
  • Three Cs: compulsory, capacity, conflict.
  • Write-through updates memory every write; write-back uses a dirty bit and writes on eviction.
  • AMAT = hit time + miss rate * miss penalty.
  • MESI keeps multicore caches coherent; watch out for false sharing.