Mini Project: A Cache-Eviction Arena
The paging lessons proved bounds: LRU and FIFO are -competitive and no deterministic rule does better (LRU and FIFO Are k-Competitive, The Lower Bound k), and the randomized marking algorithm is -competitive against an oblivious adversary, with unavoidable (The Randomized Marking Algorithm, The Harmonic Lower Bound). In this project you build an arena that replays request traces against eviction policies and reports their measured competitive ratios : realistic traces, adversarial traces generated against each deterministic policy, and Yao's hard distribution for randomized ones.
Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own. Every random choice comes from a seeded generator, so the numbers below are exactly what you will see.
Step 1: Traces, LRU, FIFO and OPT
Four trace generators cover typical access patterns:
- loop: the cycle repeated, one page more than the cache holds (LRU's and FIFO's nightmare);
- zipf: 100 pages with popularity proportional to , as in web and file caches;
- working-set: 10 hot pages around a base that drifts slowly through 200 pages, as in a program moving through its data;
- scan+hot: 200 requests to 6 hot pages, then a sequential scan over 30 cold pages, repeated, as when a database query scans a table.
The policies share one interface, access(page) returning True on a miss, and cached() returning the current contents, which the adversary of Step 3 needs. OPT is Belady's rule with precomputed next-use times and a lazy heap (Belady's Optimal Offline Rule).
import heapq
import random
from collections import OrderedDict, deque
def trace_loop(k, n):
return [t % (k + 1) for t in range(n)]
def trace_zipf(n, pages, rng):
weights = [1 / (i + 1) for i in range(pages)]
return rng.choices(range(pages), weights, k=n)
def trace_working_set(n, pages, rng, size=10, drift=0.02):
base, out = 0, []
for _ in range(n):
if rng.random() < drift:
base = (base + 1) % pages
out.append((base + rng.randrange(size)) % pages)
return out
def trace_scan(n, rng, hot=6, scan=30):
out = []
while len(out) < n:
out += [rng.randrange(hot) for _ in range(200)]
out += list(range(100, 100 + scan))
return out[:n]
class LRU:
def __init__(self, k):
self.k, self.cache = k, OrderedDict()
def access(self, p):
if p in self.cache:
self.cache.move_to_end(p)
return False
if len(self.cache) == self.k:
self.cache.popitem(last=False)
self.cache[p] = True
return True
def cached(self):
return set(self.cache)
class FIFO:
def __init__(self, k):
self.k, self.queue, self.cache = k, deque(), set()
def access(self, p):
if p in self.cache:
return False
if len(self.queue) == self.k:
self.cache.discard(self.queue.popleft())
self.queue.append(p)
self.cache.add(p)
return True
def cached(self):
return set(self.cache)
def opt_misses(reqs, k):
"""Belady's rule with next-use times and a lazy max-heap."""
n, nxt, seen = len(reqs), [0] * len(reqs), {}
for t in range(n - 1, -1, -1):
nxt[t] = seen.get(reqs[t], n + t)
seen[reqs[t]] = t
cache, heap, misses = {}, [], 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
while True:
nu, q = heapq.heappop(heap)
if cache.get(q) == -nu:
del cache[q]
break
cache[p] = nxt[t]
heapq.heappush(heap, (-nxt[t], p))
return misses
def run(policy, reqs):
return sum(policy.access(p) for p in reqs)
rng = random.Random(2026)
k, n = 8, 5000
traces = {
"loop": trace_loop(k, n),
"zipf": trace_zipf(n, 100, rng),
"working-set": trace_working_set(n, 200, rng),
"scan+hot": trace_scan(n, rng),
}
print(f"k = {k}, {n} requests per trace")
print(f"{'trace':12} {'pages':>5} {'OPT':>5} {'LRU':>5} {'FIFO':>5}")
for name, reqs in traces.items():
print(f"{name:12} {len(set(reqs)):5} {opt_misses(reqs, k):5} {run(LRU(k), reqs):5} {run(FIFO(k), reqs):5}")k = 8, 5000 requests per trace
trace pages OPT LRU FIFO
loop 9 632 5000 5000
zipf 100 2091 3236 3439
working-set 101 453 1090 1102
scan+hot 36 615 762 762
On the loop both online policies miss on every request while OPT misses about once every requests: the ratio is close to . On the realistic traces the gap is much smaller, and on scan+hot LRU and FIFO lose only a little to OPT, which knows that scanned pages will not come back soon.
Step 2: The marking algorithm
MARK evicts a uniformly random unmarked page; a page is marked when requested and all marks are cleared when every cached page is marked and a miss occurs. Being randomized, it is run with 10 seeds per trace, and the arena reports the mean, minimum and maximum number of misses.
import heapq
import random
from collections import OrderedDict, deque
def trace_loop(k, n):
return [t % (k + 1) for t in range(n)]
def trace_zipf(n, pages, rng):
weights = [1 / (i + 1) for i in range(pages)]
return rng.choices(range(pages), weights, k=n)
def trace_working_set(n, pages, rng, size=10, drift=0.02):
base, out = 0, []
for _ in range(n):
if rng.random() < drift:
base = (base + 1) % pages
out.append((base + rng.randrange(size)) % pages)
return out
def trace_scan(n, rng, hot=6, scan=30):
out = []
while len(out) < n:
out += [rng.randrange(hot) for _ in range(200)]
out += list(range(100, 100 + scan))
return out[:n]
class LRU:
def __init__(self, k):
self.k, self.cache = k, OrderedDict()
def access(self, p):
if p in self.cache:
self.cache.move_to_end(p)
return False
if len(self.cache) == self.k:
self.cache.popitem(last=False)
self.cache[p] = True
return True
def cached(self):
return set(self.cache)
class FIFO:
def __init__(self, k):
self.k, self.queue, self.cache = k, deque(), set()
def access(self, p):
if p in self.cache:
return False
if len(self.queue) == self.k:
self.cache.discard(self.queue.popleft())
self.queue.append(p)
self.cache.add(p)
return True
def cached(self):
return set(self.cache)
def opt_misses(reqs, k):
"""Belady's rule with next-use times and a lazy max-heap."""
n, nxt, seen = len(reqs), [0] * len(reqs), {}
for t in range(n - 1, -1, -1):
nxt[t] = seen.get(reqs[t], n + t)
seen[reqs[t]] = t
cache, heap, misses = {}, [], 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
while True:
nu, q = heapq.heappop(heap)
if cache.get(q) == -nu:
del cache[q]
break
cache[p] = nxt[t]
heapq.heappush(heap, (-nxt[t], p))
return misses
def run(policy, reqs):
return sum(policy.access(p) for p in reqs)
class Marking:
def __init__(self, k, rng):
self.k, self.rng, self.cache, self.marked = k, rng, set(), set()
def access(self, p):
miss = p not in self.cache
if miss:
if len(self.cache) == self.k:
if len(self.marked) == self.k: # all cached pages marked: new phase
self.marked = set()
unmarked = sorted(self.cache - self.marked)
self.cache.remove(unmarked[self.rng.randrange(len(unmarked))])
self.cache.add(p)
self.marked.add(p)
return miss
def cached(self):
return set(self.cache)
def marking_mean(reqs, k, seeds):
costs = [run(Marking(k, random.Random(seed)), reqs) for seed in seeds]
return sum(costs) / len(costs), min(costs), max(costs)
rng = random.Random(2026)
k, n = 8, 5000
traces = {
"loop": trace_loop(k, n),
"zipf": trace_zipf(n, 100, rng),
"working-set": trace_working_set(n, 200, rng),
"scan+hot": trace_scan(n, rng),
}
H = sum(1 / i for i in range(1, k + 1))
print(f"k = {k}; MARK over 10 seeds; 2H_k = {2 * H:.2f}")
print(f"{'trace':12} {'OPT':>5} {'LRU':>5} {'MARK mean':>9} {'min':>5} {'max':>5} MARK/OPT")
for name, reqs in traces.items():
opt = opt_misses(reqs, k)
mean, lo, hi = marking_mean(reqs, k, range(10))
print(f"{name:12} {opt:5} {run(LRU(k), reqs):5} {mean:9.1f} {lo:5} {hi:5} {mean / opt:8.3f}")k = 8; MARK over 10 seeds; 2H_k = 5.44
trace OPT LRU MARK mean min max MARK/OPT
loop 632 5000 1702.6 1684 1736 2.694
zipf 2091 3236 3299.8 3288 3320 1.578
working-set 453 1090 1086.3 1055 1108 2.398
scan+hot 615 762 784.4 779 793 1.275
On the loop MARK's ratio drops from about 8 to about , close to ; the analysis of the marking lesson predicts exactly for a phase with one new page. On zipf and scan+hot MARK is slightly worse than LRU: randomization buys worst-case protection at a small price on friendly traces. The spread between seeds is small, because each run averages over many phases.
Step 3: Adversaries
Two generators produce hard traces. The adaptive adversary watches a policy's cache and always requests the one page of it does not hold; against a deterministic policy this is the cruel adversary of the lower-bound lesson. The oblivious one draws requests uniformly from pages before the algorithm runs: Yao's hard distribution, on which every algorithm misses with probability per request.
import heapq
import random
from collections import OrderedDict, deque
def trace_loop(k, n):
return [t % (k + 1) for t in range(n)]
def trace_zipf(n, pages, rng):
weights = [1 / (i + 1) for i in range(pages)]
return rng.choices(range(pages), weights, k=n)
def trace_working_set(n, pages, rng, size=10, drift=0.02):
base, out = 0, []
for _ in range(n):
if rng.random() < drift:
base = (base + 1) % pages
out.append((base + rng.randrange(size)) % pages)
return out
def trace_scan(n, rng, hot=6, scan=30):
out = []
while len(out) < n:
out += [rng.randrange(hot) for _ in range(200)]
out += list(range(100, 100 + scan))
return out[:n]
class LRU:
def __init__(self, k):
self.k, self.cache = k, OrderedDict()
def access(self, p):
if p in self.cache:
self.cache.move_to_end(p)
return False
if len(self.cache) == self.k:
self.cache.popitem(last=False)
self.cache[p] = True
return True
def cached(self):
return set(self.cache)
class FIFO:
def __init__(self, k):
self.k, self.queue, self.cache = k, deque(), set()
def access(self, p):
if p in self.cache:
return False
if len(self.queue) == self.k:
self.cache.discard(self.queue.popleft())
self.queue.append(p)
self.cache.add(p)
return True
def cached(self):
return set(self.cache)
def opt_misses(reqs, k):
"""Belady's rule with next-use times and a lazy max-heap."""
n, nxt, seen = len(reqs), [0] * len(reqs), {}
for t in range(n - 1, -1, -1):
nxt[t] = seen.get(reqs[t], n + t)
seen[reqs[t]] = t
cache, heap, misses = {}, [], 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
while True:
nu, q = heapq.heappop(heap)
if cache.get(q) == -nu:
del cache[q]
break
cache[p] = nxt[t]
heapq.heappush(heap, (-nxt[t], p))
return misses
def run(policy, reqs):
return sum(policy.access(p) for p in reqs)
class Marking:
def __init__(self, k, rng):
self.k, self.rng, self.cache, self.marked = k, rng, set(), set()
def access(self, p):
miss = p not in self.cache
if miss:
if len(self.cache) == self.k:
if len(self.marked) == self.k: # all cached pages marked: new phase
self.marked = set()
unmarked = sorted(self.cache - self.marked)
self.cache.remove(unmarked[self.rng.randrange(len(unmarked))])
self.cache.add(p)
self.marked.add(p)
return miss
def cached(self):
return set(self.cache)
def marking_mean(reqs, k, seeds):
costs = [run(Marking(k, random.Random(seed)), reqs) for seed in seeds]
return sum(costs) / len(costs), min(costs), max(costs)
def cruel_adversary(policy, k, n):
"""Adaptive: always request the page of 0..k that the policy does not hold."""
reqs = []
for t in range(n):
held = policy.cached()
p = t if t < k else next(q for q in range(k + 1) if q not in held)
reqs.append(p)
policy.access(p)
return reqs
def oblivious_uniform(k, n, rng):
"""Yao's hard distribution: uniform over k + 1 pages, fixed before the algorithm runs."""
return [rng.randrange(k + 1) for _ in range(n)]
k, n = 8, 5000
H = sum(1 / i for i in range(1, k + 1))
print(f"k = {k}: deterministic bound k = {k}, H_k = {H:.2f}, 2H_k = {2 * H:.2f}")
for name, make in [("LRU", lambda: LRU(k)), ("FIFO", lambda: FIFO(k)),
("MARK (seed 1)", lambda: Marking(k, random.Random(1)))]:
reqs = cruel_adversary(make(), k, n)
opt = opt_misses(reqs, k)
alg = run(make(), reqs) # replay: the same policy, the same seed
print(f"adaptive adversary vs {name:13}: ALG {alg}, OPT {opt}, ratio {alg / opt:.2f}")
uniform = oblivious_uniform(k, n, random.Random(3))
opt = opt_misses(uniform, k)
print(f"oblivious uniform trace: OPT {opt}, LRU {run(LRU(k), uniform) / opt:.2f}, "
f"FIFO {run(FIFO(k), uniform) / opt:.2f}, MARK {marking_mean(uniform, k, range(10))[0] / opt:.2f}")k = 8: deterministic bound k = 8, H_k = 2.72, 2H_k = 5.44
adaptive adversary vs LRU : ALG 5000, OPT 632, ratio 7.91
adaptive adversary vs FIFO : ALG 5000, OPT 632, ratio 7.91
adaptive adversary vs MARK (seed 1): ALG 5000, OPT 632, ratio 7.91
oblivious uniform trace: OPT 209, LRU 2.71, FIFO 2.59, MARK 2.61
Against LRU and FIFO the adaptive adversary produces the loop and forces the full factor . Against MARK it also succeeds, but only because this adversary knows the seed: it replays MARK with the same seed, so it sees the coins, which is exactly what the oblivious model forbids (Oblivious and Adaptive Adversaries). On the oblivious uniform trace every policy lands near , as Yao's argument predicts: no algorithm, deterministic or randomized, does much better there.
Step 4: The arena
Now everything runs together: all traces, the adversarial ones generated against LRU and FIFO, three policies, one table of ratios, the worst ratio of each policy, and a check against the guarantees.
import heapq
import random
from collections import OrderedDict, deque
def trace_loop(k, n):
return [t % (k + 1) for t in range(n)]
def trace_zipf(n, pages, rng):
weights = [1 / (i + 1) for i in range(pages)]
return rng.choices(range(pages), weights, k=n)
def trace_working_set(n, pages, rng, size=10, drift=0.02):
base, out = 0, []
for _ in range(n):
if rng.random() < drift:
base = (base + 1) % pages
out.append((base + rng.randrange(size)) % pages)
return out
def trace_scan(n, rng, hot=6, scan=30):
out = []
while len(out) < n:
out += [rng.randrange(hot) for _ in range(200)]
out += list(range(100, 100 + scan))
return out[:n]
class LRU:
def __init__(self, k):
self.k, self.cache = k, OrderedDict()
def access(self, p):
if p in self.cache:
self.cache.move_to_end(p)
return False
if len(self.cache) == self.k:
self.cache.popitem(last=False)
self.cache[p] = True
return True
def cached(self):
return set(self.cache)
class FIFO:
def __init__(self, k):
self.k, self.queue, self.cache = k, deque(), set()
def access(self, p):
if p in self.cache:
return False
if len(self.queue) == self.k:
self.cache.discard(self.queue.popleft())
self.queue.append(p)
self.cache.add(p)
return True
def cached(self):
return set(self.cache)
def opt_misses(reqs, k):
"""Belady's rule with next-use times and a lazy max-heap."""
n, nxt, seen = len(reqs), [0] * len(reqs), {}
for t in range(n - 1, -1, -1):
nxt[t] = seen.get(reqs[t], n + t)
seen[reqs[t]] = t
cache, heap, misses = {}, [], 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
while True:
nu, q = heapq.heappop(heap)
if cache.get(q) == -nu:
del cache[q]
break
cache[p] = nxt[t]
heapq.heappush(heap, (-nxt[t], p))
return misses
def run(policy, reqs):
return sum(policy.access(p) for p in reqs)
class Marking:
def __init__(self, k, rng):
self.k, self.rng, self.cache, self.marked = k, rng, set(), set()
def access(self, p):
miss = p not in self.cache
if miss:
if len(self.cache) == self.k:
if len(self.marked) == self.k: # all cached pages marked: new phase
self.marked = set()
unmarked = sorted(self.cache - self.marked)
self.cache.remove(unmarked[self.rng.randrange(len(unmarked))])
self.cache.add(p)
self.marked.add(p)
return miss
def cached(self):
return set(self.cache)
def marking_mean(reqs, k, seeds):
costs = [run(Marking(k, random.Random(seed)), reqs) for seed in seeds]
return sum(costs) / len(costs), min(costs), max(costs)
def cruel_adversary(policy, k, n):
"""Adaptive: always request the page of 0..k that the policy does not hold."""
reqs = []
for t in range(n):
held = policy.cached()
p = t if t < k else next(q for q in range(k + 1) if q not in held)
reqs.append(p)
policy.access(p)
return reqs
def oblivious_uniform(k, n, rng):
"""Yao's hard distribution: uniform over k + 1 pages, fixed before the algorithm runs."""
return [rng.randrange(k + 1) for _ in range(n)]
def arena(k, n, seed):
rng = random.Random(seed)
traces = {
"loop": trace_loop(k, n),
"zipf": trace_zipf(n, 100, rng),
"working-set": trace_working_set(n, 200, rng),
"scan+hot": trace_scan(n, rng),
"uniform k+1": oblivious_uniform(k, n, rng),
"adv vs LRU": cruel_adversary(LRU(k), k, n),
"adv vs FIFO": cruel_adversary(FIFO(k), k, n),
}
rows = []
for name, reqs in traces.items():
opt = opt_misses(reqs, k)
ratios = {"LRU": run(LRU(k), reqs) / opt, "FIFO": run(FIFO(k), reqs) / opt,
"MARK": marking_mean(reqs, k, range(10))[0] / opt}
rows.append((name, opt, ratios))
return rows
k = 8
H = sum(1 / i for i in range(1, k + 1))
rows = arena(k, 5000, 2026)
print(f"competitive ratios ALG/OPT, k = {k} (MARK: mean of 10 seeds)")
print(f"{'trace':12} {'OPT':>5} {'LRU':>6} {'FIFO':>6} {'MARK':>6} best")
for name, opt, r in rows:
best = min(r, key=r.get)
print(f"{name:12} {opt:5} {r['LRU']:6.2f} {r['FIFO']:6.2f} {r['MARK']:6.2f} {best}")
worst = {p: max(r[p] for _, _, r in rows) for p in ["LRU", "FIFO", "MARK"]}
print(f"worst ratio: LRU {worst['LRU']:.2f}, FIFO {worst['FIFO']:.2f}, MARK {worst['MARK']:.2f}")
print(f"guarantees: LRU, FIFO <= k = {k}; MARK <= 2H_k = {2 * H:.2f} against oblivious traces")
print("all deterministic ratios within k:", all(r[p] <= k for _, _, r in rows for p in ["LRU", "FIFO"]))competitive ratios ALG/OPT, k = 8 (MARK: mean of 10 seeds)
trace OPT LRU FIFO MARK best
loop 632 7.91 7.91 2.69 MARK
zipf 2091 1.55 1.64 1.58 LRU
working-set 453 2.41 2.43 2.40 MARK
scan+hot 615 1.24 1.24 1.28 LRU
uniform k+1 215 2.73 2.94 2.66 MARK
adv vs LRU 632 7.91 7.91 2.69 MARK
adv vs FIFO 632 7.91 7.91 2.69 MARK
worst ratio: LRU 7.91, FIFO 7.91, MARK 2.69
guarantees: LRU, FIFO <= k = 8; MARK <= 2H_k = 5.44 against oblivious traces
all deterministic ratios within k: True
The table summarizes the course's paging results in numbers: the deterministic policies reach (almost) on adversarial traces and never exceed it; MARK's worst ratio is about , well inside its guarantee , and only an adversary that sees its coins could push it higher. On friendly traces all three policies are within a factor of OPT, and LRU is the best on two of them.
Step 5: More policies and more memory
An arena is most useful when new contenders can be added. This step adds CLOCK (the second-chance approximation of LRU used by operating systems; it is a conservative algorithm, so it is -competitive), LFU (least frequently used, which is not competitive), and LRU with slots against OPT with , the resource-augmentation comparison. A new trace, hot-set shift, switches abruptly from one small hot set to another.
import heapq
import random
from collections import OrderedDict, deque
def trace_loop(k, n):
return [t % (k + 1) for t in range(n)]
def trace_zipf(n, pages, rng):
weights = [1 / (i + 1) for i in range(pages)]
return rng.choices(range(pages), weights, k=n)
def trace_working_set(n, pages, rng, size=10, drift=0.02):
base, out = 0, []
for _ in range(n):
if rng.random() < drift:
base = (base + 1) % pages
out.append((base + rng.randrange(size)) % pages)
return out
def trace_scan(n, rng, hot=6, scan=30):
out = []
while len(out) < n:
out += [rng.randrange(hot) for _ in range(200)]
out += list(range(100, 100 + scan))
return out[:n]
class LRU:
def __init__(self, k):
self.k, self.cache = k, OrderedDict()
def access(self, p):
if p in self.cache:
self.cache.move_to_end(p)
return False
if len(self.cache) == self.k:
self.cache.popitem(last=False)
self.cache[p] = True
return True
def cached(self):
return set(self.cache)
class FIFO:
def __init__(self, k):
self.k, self.queue, self.cache = k, deque(), set()
def access(self, p):
if p in self.cache:
return False
if len(self.queue) == self.k:
self.cache.discard(self.queue.popleft())
self.queue.append(p)
self.cache.add(p)
return True
def cached(self):
return set(self.cache)
def opt_misses(reqs, k):
"""Belady's rule with next-use times and a lazy max-heap."""
n, nxt, seen = len(reqs), [0] * len(reqs), {}
for t in range(n - 1, -1, -1):
nxt[t] = seen.get(reqs[t], n + t)
seen[reqs[t]] = t
cache, heap, misses = {}, [], 0
for t, p in enumerate(reqs):
if p not in cache:
misses += 1
if len(cache) == k:
while True:
nu, q = heapq.heappop(heap)
if cache.get(q) == -nu:
del cache[q]
break
cache[p] = nxt[t]
heapq.heappush(heap, (-nxt[t], p))
return misses
def run(policy, reqs):
return sum(policy.access(p) for p in reqs)
class Marking:
def __init__(self, k, rng):
self.k, self.rng, self.cache, self.marked = k, rng, set(), set()
def access(self, p):
miss = p not in self.cache
if miss:
if len(self.cache) == self.k:
if len(self.marked) == self.k: # all cached pages marked: new phase
self.marked = set()
unmarked = sorted(self.cache - self.marked)
self.cache.remove(unmarked[self.rng.randrange(len(unmarked))])
self.cache.add(p)
self.marked.add(p)
return miss
def cached(self):
return set(self.cache)
def marking_mean(reqs, k, seeds):
costs = [run(Marking(k, random.Random(seed)), reqs) for seed in seeds]
return sum(costs) / len(costs), min(costs), max(costs)
def cruel_adversary(policy, k, n):
"""Adaptive: always request the page of 0..k that the policy does not hold."""
reqs = []
for t in range(n):
held = policy.cached()
p = t if t < k else next(q for q in range(k + 1) if q not in held)
reqs.append(p)
policy.access(p)
return reqs
def oblivious_uniform(k, n, rng):
"""Yao's hard distribution: uniform over k + 1 pages, fixed before the algorithm runs."""
return [rng.randrange(k + 1) for _ in range(n)]
class Clock:
def __init__(self, k):
self.k, self.frames, self.ref, self.hand, self.where = k, [], [], 0, {}
def access(self, p):
if p in self.where:
self.ref[self.where[p]] = True
return False
if len(self.frames) < self.k:
self.where[p] = len(self.frames)
self.frames.append(p)
self.ref.append(True)
return True
while self.ref[self.hand]:
self.ref[self.hand] = False
self.hand = (self.hand + 1) % self.k
del self.where[self.frames[self.hand]]
self.frames[self.hand], self.ref[self.hand] = p, True
self.where[p] = self.hand
self.hand = (self.hand + 1) % self.k
return True
def cached(self):
return set(self.where)
class LFU:
def __init__(self, k):
self.k, self.cache, self.freq, self.t = k, {}, {}, 0
def access(self, p):
self.t += 1
self.freq[p] = self.freq.get(p, 0) + 1
if p in self.cache:
return False
if len(self.cache) == self.k:
victim = min(self.cache, key=lambda q: (self.freq[q], self.cache[q]))
del self.cache[victim]
self.cache[p] = self.t # load time breaks ties
return True
def cached(self):
return set(self.cache)
def trace_shift(n, rng, k):
"""A hot set of k - 1 pages, then a different hot set: a trap for frequency counts."""
first = [rng.randrange(k - 1) for _ in range(n // 2)]
return first + [100 + rng.randrange(k) for _ in range(n - n // 2)]
k, n = 8, 5000
rng = random.Random(2026)
traces = {
"loop": trace_loop(k, n),
"zipf": trace_zipf(n, 100, rng),
"working-set": trace_working_set(n, 200, rng),
"hot-set shift": trace_shift(n, rng, k),
"adv vs CLOCK": cruel_adversary(Clock(k), k, n),
}
policies = {"LRU": lambda: LRU(k), "CLOCK": lambda: Clock(k), "LFU": lambda: LFU(k),
"LRU with 2k": lambda: LRU(2 * k)}
print(f"{'trace':13} {'OPT':>5} " + " ".join(f"{p:>11}" for p in policies) + f" {'MARK':>6}")
for name, reqs in traces.items():
opt = opt_misses(reqs, k)
cells = [run(make(), reqs) / opt for make in policies.values()]
mark = marking_mean(reqs, k, range(10))[0] / opt
print(f"{name:13} {opt:5} " + " ".join(f"{c:11.2f}" for c in cells) + f" {mark:6.2f}")
print(f"resource augmentation bound for LRU with 2k against OPT with k: {2 * k / (k + 1):.2f}")trace OPT LRU CLOCK LFU LRU with 2k MARK
loop 632 7.91 7.91 7.91 0.01 2.69
zipf 2091 1.55 1.59 1.15 1.14 1.58
working-set 453 2.41 2.37 8.42 0.22 2.40
hot-set shift 15 1.00 1.00 146.53 1.00 1.05
adv vs CLOCK 632 7.91 7.91 7.91 0.01 2.69
resource augmentation bound for LRU with 2k against OPT with k: 1.78
LFU is the best policy on zipf, where popularity never changes, but it collapses on the hot-set shift, keeping the old hot pages forever because of their large counts, and on the working-set trace its ratio exceeds , which no marking or conservative policy can do. CLOCK tracks LRU closely. LRU with twice the memory never exceeds the resource-augmentation bound and often beats OPT with the smaller cache outright.
Ideas for extensions
- Add the flush-when-full policy and a policy that evicts a uniformly random cached page (not just an unmarked one); compare their ratios on the loop.
- Generate an adversary for MARK that does not know the seed and must commit to its requests in advance; search over short request patterns for the one with the highest average ratio, and compare it with , the exact ratio of MARK.
- Replace the uniform distribution of Step 3 by the distribution of Yao's principle for other cache sizes , and plot the measured ratio against .
Test yourself
In Step 3, why does the adaptive adversary defeat MARK?
- MARK is deterministic
- The adversary replays MARK with the same seed, so it sees the random choices, which the oblivious model forbids
- MARK uses too few pages
- OPT is computed incorrectly
On the oblivious uniform trace over pages, why do LRU, FIFO and MARK all have ratio near ?
- They are the same algorithm
- Every online algorithm misses with probability per request, while OPT misses once per coupon-collector round of about requests
- The trace is too short
- OPT misses on every request
Which column of Step 5 can exceed , and why?
- CLOCK, because it approximates LRU
- LFU, because it is neither marking nor conservative, so the bound does not apply
- LRU with , because it has more memory
- MARK, because it is randomized