Sub topic 11
Replacement policies: LRU, FIFO and random
This chapter assumes you can split an address into tag, index and offset. It also assumes you know how direct-mapped, fully associative and k-way set-associative caches place blocks. You should be comfortable counting hits and misses on a reference string.
When a replacement policy is needed
A replacement policy answers one question: when a set has no free line, which resident block should be evicted? The policy runs only when two conditions hold at once:
- The access is a miss.
- Every line in the target set is valid, so there is no empty line to fill.
Lines that are not yet valid are filled first, and no block is evicted. This is why the first few misses in an empty cache are compulsory misses with no eviction.
The number of candidate victims equals the associativity.
| Organization | Candidates for eviction | Policy needed? |
|---|---|---|
| Direct-mapped | 1 (the only line in the set) | No |
| k-way set-associative | k lines in the set | Yes, per set |
| Fully associative | All lines in the cache | Yes, across the cache |
A fully associative cache is the special case of one set containing all lines. Every policy below therefore applies to a single set, and you can treat a fully associative cache as a set-associative cache with one set.
The three policies
LRU: least recently used
LRU evicts the block whose last access is oldest. It relies on temporal locality: a block used recently is likely to be used again soon, so the block unused for the longest time is the best candidate to drop.
LRU must update its state on every hit as well as every miss. A hit moves the block to the most-recently-used position.
FIFO: first in, first out
FIFO evicts the block that has been in the set longest, regardless of how often it was used. State changes only when a block is loaded. A hit does not change the order.
Random
Random evicts a randomly chosen line in the set. It needs no per-block usage history, only a random or pseudo-random number generator. Its behavior is not reproducible, so GATE questions rarely ask for exact random traces. They may ask about its hardware cost or its expected behavior.
A worked trace: no policy always wins
Take one set with 2 ways and the reference string A B A C B. The set starts empty.
| Access | LRU result | LRU set (oldest to newest) | FIFO result | FIFO set (oldest to newest) |
|---|---|---|---|---|
| A | miss | A | miss | A |
| B | miss | A B | miss | A B |
| A | hit | B A | hit | A B |
| C | miss, evict B | A C | miss, evict A | B C |
| B | miss, evict A | C B | hit | B C |
LRU gets 1 hit and 4 misses. FIFO gets 2 hits and 3 misses. FIFO wins here because LRU's hit on A made A look recent. LRU then threw out B, which was needed next.
The reverse also happens. If a hot block is loaded early and reused constantly, FIFO eventually evicts it because it is the oldest, while LRU keeps it. In general, LRU does better on typical programs, but a specific trace can favor any policy.
Simulating the policies
This simulator takes block numbers (the tag and index together) and supports all three policies. It uses block % num_sets as the set index, which matches the index bits when num_sets is a power of two. Set num_sets=1 for a fully associative cache.
from collections import OrderedDict
import random
def simulate(blocks, num_sets, ways, policy="LRU", seed=0):
rng = random.Random(seed)
sets = [OrderedDict() for _ in range(num_sets)]
hits = 0
for b in blocks:
s = sets[b % num_sets]
if b in s:
hits += 1
if policy == "LRU":
s.move_to_end(b) # most recently used goes last
else:
if len(s) == ways:
if policy == "RANDOM":
del s[rng.choice(list(s))]
else: # LRU and FIFO both evict the front
s.popitem(last=False)
s[b] = True # new block goes last
return hits, len(blocks) - hits
print(simulate(["A", "B", "A", "C", "B"], 1, 2, "LRU")) # (1, 4)
print(simulate(["A", "B", "A", "C", "B"], 1, 2, "FIFO")) # (2, 3)The only difference between LRU and FIFO in the code is the move_to_end call on a hit. That one line is the whole distinction: LRU reorders on hits, FIFO does not.
The trace-based method is the one to use on exam questions. Keep one ordered list per set. Write the victim end on the left. For LRU, rewrite the list on every access. For FIFO, change it only on misses.
Belady's anomaly
Giving a cache more capacity should not hurt, but under FIFO it sometimes does. Use a fully associative cache and the string 1 2 3 4 1 2 5 1 2 3 4 5.
trace = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for frames in (3, 4):
print(frames, "FIFO", simulate(trace, 1, frames, "FIFO"))
print(frames, "LRU ", simulate(trace, 1, frames, "LRU"))
# 3 FIFO (3, 9)
# 3 LRU (2, 10)
# 4 FIFO (2, 10)
# 4 LRU (4, 8)FIFO goes from 9 misses with 3 frames to 10 misses with 4 frames. This is Belady's anomaly. LRU does not show it, because LRU is a stack algorithm. At any moment, the set of blocks held with k frames is a subset of those held with k+1 frames, so adding capacity cannot cause new misses. Random is not a stack algorithm either, so it can behave oddly on a specific run.
The cyclic-access failure
Consider a loop that touches k+1 distinct blocks in order, repeatedly, which all map to a k-way set. Under LRU, each access evicts exactly the block that will be needed next. The hit count is zero after the initial fill. FIFO behaves the same way on this pattern.
Random breaks the pattern. It sometimes keeps a block that is about to be reused, so it gets some hits.
loop = [0, 1, 2, 3] * 10
print(simulate(loop, 1, 3, "LRU")) # (0, 40)
print(simulate(loop, 1, 3, "FIFO")) # (0, 40)
print(simulate(loop, 1, 3, "RANDOM")) # more than 0 hitsThis is also why a "bad for LRU" question usually involves a loop slightly larger than the cache or the set.
Hardware cost
The cost of tracking state grows with associativity, which is why real caches approximate LRU.
| Policy | State per set | Updated on |
|---|---|---|
| True LRU | Order of k lines, so ⌈log₂(k!)⌉ bits at minimum, or k·log₂k bits with per-line counters | Every access |
| Tree pseudo-LRU | k − 1 bits | Every access |
| FIFO | One pointer, log₂k bits | Misses only |
| Random | None per set, one shared generator | Nothing |
For a 4-way set, true LRU needs at least ⌈log₂ 24⌉ = 5 bits, and a counter scheme uses 4 × 2 = 8 bits. Tree pseudo-LRU uses 3 bits. For a 2-way set, LRU needs just 1 bit per set, which says which of the two lines is older.
Interactions with other topics
- Write-back: the victim chosen by the policy may be dirty. Evicting it costs an extra write to the next level, so the miss penalty is higher for dirty victims.
- Conflict misses: a better policy lowers conflict misses in associative caches but cannot remove capacity or compulsory misses. A direct-mapped cache has no choice, so only increasing associativity helps there.
- Hit updates: only LRU needs state changes on hits. In a timing question, that is why an LRU hit costs slightly more hardware effort than a FIFO hit.
Common errors
- Updating FIFO order on a hit. FIFO order changes only when a block is loaded.
- Forgetting that LRU order is tracked per set. Blocks in different sets never compete.
- Evicting when an invalid line is available. Fill empty lines first.
- Applying a policy to a direct-mapped cache. There is exactly one candidate.
- Mixing up index and tag when assigning blocks to sets before tracing. Work out each block's set first, then trace each set separately.
Exercise
A 2-way set-associative cache has 2 sets and starts empty. The block-number reference string is 0 2 4 0 2 4 1 3 0. Block b maps to set b mod 2. Count hits under LRU and under FIFO.
Show answer
Set 0 receives blocks 0, 2, 4, 0, 2, 4, 0. Set 1 receives 1 and 3, which are 2 compulsory misses under either policy. LRU in set 0: 0 miss, 2 miss, 4 miss (evict 0), 0 miss (evict 2), 2 miss (evict 4), 4 miss (evict 0), 0 miss (evict 2). That is 0 hits, because three blocks cycle through two ways. FIFO behaves the same way on this cyclic pattern: 0 hits. Total: 0 hits and 9 misses under both policies.
Exercise
A fully associative cache holds 3 blocks. For the string 1 2 3 4 1 2 5 1 2 3 4 5, LRU gives 2 hits. What happens to the number of hits under LRU if the cache grows to 4 blocks, and why can this never go down for LRU?
Show answer
Hits rise from 2 to 4. LRU is a stack algorithm: the blocks held with 3 frames are always a subset of the blocks held with 4 frames, so any access that hits with 3 frames also hits with 4. This is why LRU has no Belady's anomaly, while FIFO does (FIFO falls from 3 hits to 2 on this string).
Exercise
How many bits per set does a true LRU scheme need at minimum for a 4-way set, and how many does tree pseudo-LRU need?
Show answer
True LRU must distinguish 4! = 24 orderings, so it needs at least ⌈log₂ 24⌉ = 5 bits per set. Tree pseudo-LRU needs k − 1 = 3 bits per set.