6. Memory Hierarchy and Cache Basics
Description
Fast memory is small and expensive; large memory is slow and cheap. A memory hierarchy stacks levels so most accesses hit the fast ones:
Registers → L1 → L2 → L3 → DRAM → SSD → HDD
It works because of the principle of locality:
- Temporal locality: recently used data is likely to be used again soon.
- Spatial locality: data near recently used data is likely to be used soon.
A cache is a small, fast memory between the CPU and main memory that holds copies of recently used blocks.
Terms: hit (data found), miss (not found), block/line (unit of transfer, e.g. 64 B), set (group of places a block may go), tag (identifies which block is stored), valid bit, dirty bit.
Placement (mapping):
| Type | Rule | Trade-off |
|---|---|---|
| Direct-mapped | Each block goes to exactly one line (index = block address mod lines) | Fast, simple, most conflicts |
| Set-associative (n-way) | Block can go to any of n lines in one set | Balanced; common in practice |
| Fully associative | Block can go anywhere | Fewest conflicts, costly comparators |
Replacement: LRU (least recently used), random, FIFO.
Write policies:
- Write-through: write to cache and memory immediately (simple, more memory traffic; often used with a write buffer).
- Write-back: write only to cache, mark the line dirty, write to memory on eviction (less traffic, more complex).
- Write-allocate (fetch the block on a write miss, usual with write-back) vs no-write-allocate (write straight to memory, usual with write-through).
Three Cs of misses (a fourth, coherence, appears in multiprocessors):
- Compulsory: first access to a block (cold start).
- Capacity: the cache cannot hold the working set.
- Conflict: too many blocks map to the same set.
Key Formulas
AMAT = Hit time + Miss rate × Miss penalty
Two-level: AMAT = HitTime_L1 + MissRate_L1 × (HitTime_L2 + LocalMissRate_L2 × MissPenalty_L2)
Memory-stall cycles per instruction
= (memory accesses / instruction) × miss rate × miss penalty
CPU time = IC × (CPI_base + stall cycles/instr) × T
Address split (byte address):
| Tag | Index | Block offset |
offset bits = log2(block size)
index bits = log2(number of sets)
tag bits = address bits − index bits − offset bits
Number of blocks = cache size / block size
Number of sets = blocks / associativity
Steps
To split an address: (1) offset = log₂(block size), (2) sets = (cache size ÷ block size) ÷ associativity, (3) index = log₂(sets), (4) tag = remaining bits.
To simulate a cache lookup: (1) compute set index, (2) compare the tag with all valid lines in the set, (3) match → hit (update LRU), (4) no match → miss: fetch block, evict LRU (write back if dirty).
To compute AMAT: (1) identify hit time, miss rate, miss penalty at each level, (2) work from the lowest level upward.
Worked Example
A. AMAT. Hit time 1 cycle, miss rate 5%, miss penalty 100 cycles: AMAT = 1 + 0.05 × 100 = 6 cycles.
B. Two-level AMAT. L1 hit 1 cycle, L1 miss rate 5%; L2 hit 10 cycles, L2 local miss rate 40%; memory 100 cycles. AMAT = 1 + 0.05 × (10 + 0.4 × 100) = 1 + 0.05 × 50 = 3.5 cycles.
C. Address split, 4-way. 32-bit address, 32 KB cache, 64 B blocks, 4-way. Blocks = 32768/64 = 512; sets = 512/4 = 128 → offset = 6 bits, index = 7 bits, tag = 32 − 7 − 6 = 19 bits.
D. Address split, direct-mapped. 4 KB cache, 16 B blocks: 256 lines → offset 4, index 8, tag 20 bits.
E. Effect on CPI. Base CPI 1.0; instruction miss rate 2%, data miss rate 4%, 36% of instructions access data, miss penalty 100 cycles. Stalls = 0.02 × 100 + 0.36 × 0.04 × 100 = 2 + 1.44 = 3.44. CPI = 4.44, so the memory system makes the machine 4.4× slower than the ideal.
F. Mapping comparison. Block-address stream 0, 8, 0, 6, 8 in a cache with 4 blocks (LRU).
| Organization | Result | Misses |
|---|---|---|
| Direct-mapped (index = addr mod 4) | 0 miss, 8 miss (evicts 0), 0 miss, 6 miss, 8 miss | 5 |
| 2-way (2 sets, index = addr mod 2) | 0 miss, 8 miss, 0 hit, 6 miss (evicts 8), 8 miss | 4 |
| Fully associative | 0 miss, 8 miss, 0 hit, 6 miss, 8 hit | 3 |
More associativity removes conflict misses.
G. Spatial locality. Summing an array sequentially with 4-byte words and 64 B blocks: one miss per 16 accesses → 6.25% miss rate (compulsory only).
Python / Assembly
def simulate(addrs, num_blocks, assoc):
sets = num_blocks // assoc
cache = [[] for _ in range(sets)] # each set: list, LRU at index 0
misses = 0
for a in addrs:
s = a % sets
if a in cache[s]:
cache[s].remove(a); cache[s].append(a) # hit: move to MRU
else:
misses += 1
if len(cache[s]) == assoc:
cache[s].pop(0) # evict LRU
cache[s].append(a)
return misses
stream = [0, 8, 0, 6, 8]
print([simulate(stream, 4, w) for w in (1, 2, 4)]) # [5, 4, 3]
def amat(hit, miss_rate, penalty):
return hit + miss_rate * penalty
print(amat(1, 0.05, 100)) # 6.0
Sequential array sum (good spatial locality):
li t0, 0 # sum
la a0, A # base address
li a1, 1000 # element count
loop: lw t1, 0(a0) # one miss per cache block, then hits
add t0, t0, t1
addi a0, a0, 4
addi a1, a1, -1
bnez a1, loop
Notes
- Use the local miss rate for L2 in the two-level formula; global miss rate = L1 miss rate × L2 local miss rate.
- Bigger caches cut capacity misses but raise hit time; higher associativity cuts conflict misses but raises hit time and energy.
- Bigger blocks use spatial locality but raise miss penalty and can cause pollution.
- A browser cache is an analogy, but the same idea (keep what you reuse; evict the least recently used) applies.
- Quick facts: cache mapping types are direct, associative and set-associative; a miss forces a fetch from slower memory; larger cache reduces misses.
References: [HP6] Ch. 2 (2.1-2.2), Appendix B (B.1-B.3); [PH-RV] Ch. 5 (5.1-5.4);
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me