Online algorithms and competitive analysis
Many decisions are made without knowing the future: cache eviction, when to buy rather than rent, or which server receives a request. Competitive analysis compares against an optimum that knows the future. Study deterministic and randomized ski rental, LRU paging and its k bound, randomized marking and H_k, Yao's minimax principle and an O(1) LRU cache.
After this lesson you can
- Calculate competitive ratios and construct adversarial inputs.
- Prove the ski-rental ratio 2 and derive the optimal randomized strategy.
- Prove LRU is k-competitive and no deterministic algorithm improves it.
- Apply Yao's principle to lower-bound randomized algorithms.
- Implement an O(1) LRU cache and compare it with Belady on real traces.
Before you start
Motivation: decide without knowing the future
Every time your CPU reads a memory address, its L1 cache has a few nanoseconds to decide which line to evict if the needed one is absent. A CDN node decides what videos to keep on disk without knowing tomorrow’s requests. An LLM server such as vLLM keeps KV-cache blocks for computed prefixes on GPU to avoid recomputing them for later requests with the same beginning, and when memory fills evicts least-recently-used free blocks (see prefix caching). In all three, the decision is made now and its quality depends on requests not yet received.
This is not just about caches. Pay for a one-year reserved instance or continue hourly? Should a thread awaiting a lock spin or sleep, given a fixed sleep-and-wake cost? Which server receives a request now when future requests are unknown? Each has the same form: requests revealed one by one and irrevocable decisions made on arrival.
You know two ways to analyze operation sequences. Amortized analysis bounds total cost of any sequence without comparison. The streaming model limits memory, not information: the algorithm sees data in order but answers only at the end. Here information is limited and the yardstick differs: compare algorithm cost with an offline optimum knowing the entire sequence in advance. The worst-case ratio is the competitive ratio, developed through two canonical problems: ski rental and paging.
The online model and competitive ratio
An online minimization problem consists of requests and state (cache contents, whether equipment has been bought). An online algorithm receives , must serve it using an action depending only on , and pays a cost. Let be total cost and the minimum cost attainable by an algorithm knowing all of , the offline optimum.
Three comments. First, this is a relative worst-case bound: it does not say the algorithm is cheap, only that it is never much worse than the best possible on the same input. A sequence expensive for everyone, including OPT, does not penalize it. Second, additive constant absorbs startup effects (the cache starts empty), but can trivialize bounded-cost problems; in ski rental, for example, reasonable cost is at most , so strict competitiveness is used. Third, there is no computation-time assumption: OPT can be NP-hard to compute, and the online algorithm exponential. The measure is the price of not knowing, not inability to compute, distinguishing it from approximation ratio.
The definition describes a game. The designer picks the algorithm, then an adversary picks the sequence hurting it most. With a deterministic algorithm the adversary can simulate it and knows every response. With randomness, what the adversary sees matters:
- Oblivious adversary. Knows the algorithm, including its coin distribution, but fixes the whole sequence before the coins are tossed. This is the model above and makes sense when requests come from the world, not an observer of decisions.
- Adaptive online adversary. Constructs while seeing algorithm decisions through , but must also serve its own sequence online.
- Adaptive offline adversary. Sees decisions while constructing the sequence and finally pays the offline optimum for that sequence.
The third is strong enough to nullify randomness: Ben-David, Borodin, Karp, Tardos and Wigderson (1994) proved that if a randomized algorithm is -competitive against adaptive offline adversaries, a deterministic -competitive algorithm exists. All randomization gains below are against oblivious adversaries.
Ski rental
You ski without knowing how many days: the season ends when snow runs out or you are injured, and you learn only that morning. Renting costs 1 per day; buying costs (an integer) and nothing afterward. If the season lasts days, offline optimum is obvious: . This is ski rental, prototype of rent-or-buy dilemmas: reserved instances, spinning or sleeping on locks, powering down or keeping disks on.
A deterministic algorithm receives no information beyond “the season continues,” so is described by one number: day on which it buys if still skiing (rent on days and buy at the start of day ). Its cost is
The adversary sees one weakness: end the season on the day you buy, when you have paid rent and purchase without enjoying anything afterward.
Proof
Upper bound with : if the algorithm pays ; if it pays and OPT pays , ratio . Lower bound: the figure suggests the argument (the adversary ends the season on purchase day ), completed in the final guided exercise.
∎Randomize: make the adversary indifferent
Against an oblivious adversary a randomized strategy is a distribution over purchase day. The idea making it optimal comes from zero-sum games: if the adversary knows which hurts you most, it chooses that; the best defense makes every equally bad. The continuous version is cleaner: time is real, rental costs 1 per time unit and purchase occurs at time drawn with density .
Proof
For , the algorithm pays if buying at and if not yet bought:
Require for every . Differentiating with respect to cancels terms , leaving . Differentiate again: , so . Normalization fixes , and evaluating the first derivative at gives . For cost does not change (purchase is certain by then) and , so ratio remains . In the discrete version, the same reasoning with differences gives ; equating it to for every forces , and normalization gives .
∎The figure shows two things. Density increases: the optimal strategy buys rather late but keeps early-purchase probability so a long season is not too expensive. And shape matters: uniform on gives expected cost , whose ratio tends to 2 as . Randomness alone does not help; the distribution equalizing all cases does. Is best possible? Yes, as Yao’s principle will show.
A potential analysis: move to front
Before paging, a short example shows how competitive analysis and the potential method combine, and started the field. A linked list of elements receives access requests; accessing position costs , moving the accessed element forward is free and any other adjacent swap costs 1. Move to front (MTF) moves every accessed element to the head.
Proof
Let count inversions between MTF’s and OPT’s lists: pairs in different orders. It starts at 0 and is never negative. On access to , let count elements before in both lists and those before it in MTF but after it in OPT. MTF pays ; moving to the head destroys inversions with those elements and creates at most , so . OPT pays at least for access; its free swaps can only remove inversions and each paid swap creates at most one, so if it makes paid swaps, rises by at most . MTF’s amortized step cost is , less than twice OPT’s payment. Summing, final potential is nonnegative and initial potential 0.
∎Potential measures distance between algorithm and optimum states and pays their cost difference. This idea reappears in splay trees, doing the same with trees instead of lists, and the still-open dynamic optimality conjecture.
Paging
The central competitive-analysis problem. Fast memory holds pages and slow memory the rest. Each request is a page; if fast memory contains it, a hit costs nothing; otherwise a page fault costs 1, brings it in and, if full, evicts another. The algorithm chooses only which page to evict. Assume demand paging (a page loads only on request); prefetching will soon be shown not to help. This is the external-memory model with block size 1 and no control over access order.
Offline optimum: farthest in the future
Proof
Count loads rather than faults and allow schedules loading unrequested pages. They gain nothing: every anticipatory load of can be delayed until the next request for (or removed if none) without increasing loads, so a demand schedule attains the minimum over all schedules.
Let be an optimal demand schedule agreeing with FF on its first requests. Construct another optimal agreeing with FF on its first ; iteration yields FF. If request is a hit or evicts what FF does, set . Otherwise let be the requested page, the one FF evicts and the one evicts. Let evict then imitate . Caches differ only because has and has , until the first event below (if neither occurs, makes exactly ’s loads):
- evicts to bring another page . evicts and brings : same loads and identical caches thereafter.
- is requested. faults and hits. If evicts to bring , caches equalize and has one fewer load. If it evicts another page , evicts and preloads : caches equalize with the same loads.
cannot be requested before : FF chose precisely because its next request was farthest away. In all cases makes no more loads than , agrees with FF at step and, after eliminating its preloads as above, still agrees.
∎Belady is not online because it needs the future, but is the yardstick. It explains why results here concern ratios: ideal cache contents depend on requests the online algorithm has not seen.
LRU, FIFO and relatives
Classic online policies evict according to the past. LRU (least recently used) evicts the page with the oldest last use; FIFO the longest in cache, even if used frequently; LFU (least frequently used) the fewest accesses. CLOCK, used by many operating systems, cheaply approximates LRU with one use bit per page. The first three are the paging and LRU policies studied here.
The figure shows every deterministic policy’s weakness. With pages requested in a loop, LRU caches exactly the last and the requested page is the one missing: every access faults. Belady evicts the page returning latest and faults once every requests. Ratio is no LRU accident.
To analyze policies together, define phases: the first starts at the first request and each is the maximal segment with at most distinct pages; the next starts with distinct page number . An algorithm is conservative if any request segment with at most distinct pages incurs at most faults. LRU is conservative: a page requested in such a segment stays among the most recently used until it ends. FIFO is too: if page faulted twice in the segment, FIFO must have evicted it between them, possible only when is the oldest page of a full cache, after loading other pages still cached plus the eviction-triggering page; with , the segment would have distinct pages. (Young, 1994, introduced conservative algorithms.)
Part 1 follows from two phase observations: a conservative algorithm faults at most times per phase, and OPT faults at least once on each segment from a phase’s second request to the next phase’s first. A guided exercise gives the full proof; resource augmentation generalizes it. Part 2 is the loop against any algorithm:
Proof
Let be deterministic and consider pages. Since the adversary can simulate , each step requests the sole one of pages missing from ’s cache (after filling it with initial requests). Thus faults on every one of requests. To bound OPT use Belady: when it faults at time requesting and evicts , its cache contains every page except , and its next fault is the next request for . Since was the latest-returning of the cached pages before the fault, the other are requested first, so at least requests separate consecutive Belady faults. Therefore , and if for every , with we get .
∎LFU is worse: it is not competitive at all. With , request page a million times then alternate . LFU protects with a million accumulated uses and faults on each alternating request for a long time, while OPT evicts and faults no more. No constant bounds the ratio. In the lab a real matrix-multiplication trace shows it: with good loop order, LFU has almost 8 times Belady’s faults.
Randomness: the marking algorithm
Bound arises because the adversary knows which page is absent. If eviction is random, an oblivious adversary no longer knows.
Algorithm phases match the earlier -distinct-page phases: a marked page is never evicted, and marks clear exactly when distinct page number arrives. LRU is a deterministic marking algorithm (the least recently used page is never marked if any is unmarked); randomized marking changes only eviction choice. It is Las Vegas: requests are always served correctly; only cost is random.
Proof
Number phases . A page of phase is new if not requested in phase and old otherwise; let count new pages in phase (in the first, with empty cache, all are new: ).
OPT pays at least half the new pages. Phases and together request at least distinct pages, and at phase start OPT caches at most : it faults at least times in those phases. Summing over the pairs, whose phase pairs are disjoint, ; summing odd pairs (with phase 1 alone) gives . Thus .
Marking pays at most per new page. At phase start the cache holds exactly the pages of phase , all unmarked. Each new page causes exactly one fault. For old pages use indicators: let indicate whether the -th distinct old page requested in the phase faults on first request (later ones hit because it is marked). At that point old pages are unrequested. Marked pages occupy slots, where counts new pages requested so far, and the rest of cache, slots, are unrequested old pages: exactly are absent. Since the adversary is oblivious, sequence is independent of coins, and each eviction selects uniformly among unmarked pages; by symmetry the missing form a uniform subset of unrequested old pages. Thus , and by linearity
Summing, .
∎The improvement is huge: versus 64. Exact analysis (Achlioptas, Chrobak and Noga, 2000) gives for this algorithm, and more elaborate randomized algorithms attain exactly , such as Partition (McGeoch and Sleator, 1991). In the figure’s -page loop, marking averages about faults per phase versus Belady’s one: on that trace the proof’s bound is exact because each phase has one new page.
Lower bounds: Yao’s principle
Can a randomized algorithm beat ? Proving not would require reasoning over all distributions over all algorithms. Yao’s principle replaces this with a manageable task: reason about one input distribution and deterministic algorithms.
Proof
Worst case is at least the average over , and expectations can be interchanged: . For the competitive version, if for all , average over and use the inequality above to get ; divide and let grow to obtain .
∎The inequality is the easy half of an equality. The game between designer (rows, mixed strategies ) and adversary (columns, mixed strategies ) is a zero-sum minimax problem, and von Neumann’s theorem makes the best randomized algorithm against worst case cost exactly the same as the best deterministic one against the worst input distribution. Yao’s minimax principle says one bad distribution suffices for a lower bound, and duality guarantees the optimal bound can always be obtained this way.
Proof
Take pages and independent uniform requests over them of length . For a deterministic algorithm, request is independent of its current cache, holding at most of pages: it faults with probability at least , and . For OPT use Belady: if it faults at requesting and evicts , its next fault is the next request for , before which all other cached pages are requested. Between consecutive faults all distinct pages of therefore appear, and waiting for specific coupons among equiprobable ones takes requests on average (coupon collector). By the renewal-process law of large numbers, , and the ratio of expectations tends to at least . Yao concludes.
∎The same argument proves the exponential strategy optimal for ski rental: a season-duration distribution exists against which no deterministic purchase day beats in the discrete version (or continuous). The lab computes it by solving the game as a linear program; both optimal strategies, designer and adversary, emerge from primal and dual.
Resource augmentation
Result compares LRU to an optimum with the same cache. Sleator and Tarjan observed that giving the online algorithm a little more memory removes pessimism.
Proof
Divide the sequence into phases of distinct pages, total. LRU faults at most times per phase because it is conservative: . Let be phase ’s first page and consider the segment from phase ’s second request to phase ’s first. It contains the pages of phase other than and the opening page of phase , which differs from all of them: at least pages distinct from . At the segment’s start OPT has just served , so holds and at most other pages; at least of those pages are absent and each causes a fault within the segment. Segments from different phases are disjoint, so . Combining, .
∎With this is exactly -competitiveness. In the race, lower on the -page loop and watch LRU and Belady curves approach; in the lab, with long traces, and , measured ratio is , exactly bound . This is an early beyond-worst-case analysis: doubling cache is inexpensive in hardware and turns a useless guarantee into a very good one.
An O(1) LRU cache
Implementing LRU with a recency-ordered list is natural and slow: accessing a page requires finding and moving it to the end, and list.remove traverses the list, per access. The correct structure combines two familiar pieces. A hash table maps each key to its node in expected ; a doubly linked list maintains recency and removes a node given its pointer or inserts it at the head by rewriting a fixed number of pointers. Two sentinel nodes at the ends eliminate empty-list special cases. This is the O(1) LRU cache.
Two details matter in any implementation. The node stores its key because evicting the last node must also delete it from the table, and only the node is available. And cost has two qualifications: list operations are worst-case , but hash-table operations are expected-time, and occasional resizing makes cost also amortized.
Lab 1: cache-policy simulator
Start with the figure’s structure from scratch, checked against OrderedDict and measured against list.remove.
import random, time
from collections import OrderedDict
class _Nodo:
__slots__ = ("clave", "valor", "prev", "next")
def __init__(self, clave=None, valor=None):
self.clave, self.valor = clave, valor
self.prev = self.next = None
class LRUCache:
"""Caché LRU: diccionario clave -> nodo y lista doblemente enlazada con centinelas."""
def __init__(self, capacidad):
self.cap = capacidad
self.tabla = {}
self.cabeza, self.cola = _Nodo(), _Nodo() # centinelas: nunca hay que comprobar None
self.cabeza.next, self.cola.prev = self.cola, self.cabeza
def _desenganchar(self, nodo): # 2 punteros
nodo.prev.next, nodo.next.prev = nodo.next, nodo.prev
def _al_frente(self, nodo): # 4 punteros
nodo.prev, nodo.next = self.cabeza, self.cabeza.next
self.cabeza.next.prev = nodo
self.cabeza.next = nodo
def get(self, clave, defecto=None):
nodo = self.tabla.get(clave)
if nodo is None:
return defecto
self._desenganchar(nodo)
self._al_frente(nodo)
return nodo.valor
def put(self, clave, valor):
"""Inserta o actualiza; devuelve la clave desalojada (o None)."""
nodo = self.tabla.get(clave)
if nodo is not None:
nodo.valor = valor
self._desenganchar(nodo)
self._al_frente(nodo)
return None
desalojada = None
if len(self.tabla) == self.cap:
viejo = self.cola.prev
self._desenganchar(viejo)
del self.tabla[viejo.clave] # por eso el nodo guarda su clave
desalojada = viejo.clave
nodo = _Nodo(clave, valor)
self.tabla[clave] = nodo
self._al_frente(nodo)
return desalojada
def claves(self):
"""De la más reciente a la menos reciente."""
out, n = [], self.cabeza.next
while n is not self.cola:
out.append(n.clave)
n = n.next
return out
# comprobación contra OrderedDict en 20000 operaciones aleatorias
random.seed(0)
mia, ref = LRUCache(8), OrderedDict()
for _ in range(20000):
c = random.randrange(20)
if random.random() < 0.5:
r2 = ref.get(c)
if c in ref:
ref.move_to_end(c)
assert mia.get(c) == r2
else:
mia.put(c, c * c)
ref[c] = c * c
ref.move_to_end(c)
if len(ref) > 8:
ref.popitem(last=False)
assert mia.claves() == list(reversed(ref))
print("20000 operaciones: idéntica a OrderedDict")
class LRUConLista:
"""La versión ingenua: una lista con la más reciente al final y list.remove."""
def __init__(self, capacidad):
self.cap, self.orden, self.datos = capacidad, [], {}
def get(self, clave, defecto=None):
if clave not in self.datos:
return defecto
self.orden.remove(clave) # recorre la lista: O(k)
self.orden.append(clave)
return self.datos[clave]
def put(self, clave, valor):
if clave in self.datos:
self.orden.remove(clave)
elif len(self.datos) == self.cap:
del self.datos[self.orden.pop(0)] # pop(0) también es O(k)
self.orden.append(clave)
self.datos[clave] = valor
def microsegundos(Cache, k, m=4000):
c = Cache(k)
for i in range(k):
c.put(i, i)
rnd = random.Random(1)
claves = [rnd.randrange(k) for _ in range(m)]
t0 = time.perf_counter()
for x in claves:
c.get(x)
return 1e6 * (time.perf_counter() - t0) / m
print(f"{'k':>6} {'dict + lista enlazada':>22} {'list.remove':>12} (µs por acceso)")
for k in (10, 1000, 10000):
print(f"{k:>6} {microsegundos(LRUCache, k):>22.2f} {microsegundos(LRUConLista, k):>12.2f}")The linked-list column stays fixed when increases a thousandfold; list.remove grows linearly. With they cost the same, explaining why small tests miss the mistake.
Now five policies. Simulation only needs fault counts, so LRU uses OrderedDict (internally a dictionary with doubly linked list) and Belady a heap of next uses.
import heapq, random
from collections import OrderedDict, deque
def fallos_lru(traza, k):
cache, f = OrderedDict(), 0
for p in traza:
if p in cache:
cache.move_to_end(p)
else:
f += 1
if len(cache) == k:
cache.popitem(last=False)
cache[p] = True
return f
def fallos_fifo(traza, k):
cache, cola, f = set(), deque(), 0
for p in traza:
if p not in cache:
f += 1
if len(cache) == k:
cache.discard(cola.popleft())
cache.add(p)
cola.append(p)
return f
def fallos_lfu(traza, k):
"""Frecuencia mientras la página está en caché; a igualdad, la usada hace más tiempo."""
freq, ultimo, f = {}, {}, 0
for t, p in enumerate(traza):
if p not in freq:
f += 1
if len(freq) == k:
del freq[min(freq, key=lambda q: (freq[q], ultimo[q]))]
freq[p] = 0
freq[p] += 1
ultimo[p] = t
return f
def fallos_marcado(traza, k, semilla=0):
rnd = random.Random(semilla)
cache, marcadas, f = set(), set(), 0
for p in traza:
if p not in cache:
f += 1
if len(cache) == k:
if len(marcadas) == k: # todas marcadas: empieza una fase
marcadas.clear()
cache.remove(rnd.choice(sorted(cache - marcadas)))
cache.add(p)
marcadas.add(p)
return f
def fallos_belady(traza, k):
"""El más lejano en el futuro, en O(n log n) con un montículo perezoso."""
n = len(traza)
prox, visto = [0] * n, {}
for t in range(n - 1, -1, -1):
prox[t] = visto.get(traza[t], n + t) # n + t: «no vuelve», con desempate estable
visto[traza[t]] = t
en_cache, heap, f = {}, [], 0 # en_cache[p] = próximo uso vigente de p
for t, p in enumerate(traza):
if p not in en_cache:
f += 1
if len(en_cache) == k:
while True: # descarta entradas caducadas
nu, q = heapq.heappop(heap)
if en_cache.get(q) == -nu:
del en_cache[q]
break
en_cache[p] = prox[t]
heapq.heappush(heap, (-prox[t], p))
return f
POLITICAS = {"LRU": fallos_lru, "FIFO": fallos_fifo, "LFU": fallos_lfu,
"marcado": fallos_marcado, "Belady": fallos_belady}
s = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
for k in (3, 4):
print(f"k = {k}:", {nombre: f(s, k) for nombre, f in POLITICAS.items() if nombre != "marcado"})The short trace is Belady’s anomaly: FIFO faults 9 times with 3 frames and 10 with 4. More memory, more faults. LRU and Belady cannot suffer it because cache contents with frames are always contained in those with (stack algorithms); FIFO lacks that property.
The main experiment compares five policies on synthetic traces and one from a real program: memory pages read from and by matrix multiplication of row-major doubles, with 4 doubles per page and two loop orders.
import random
def traza_bucle(n, k):
return [t % (k + 1) for t in range(n)]
def traza_zipf(n, paginas, s=1.0, semilla=0):
rnd = random.Random(semilla)
return rnd.choices(range(paginas), weights=[1 / (i + 1) ** s for i in range(paginas)], k=n)
def traza_escaneo(n, k, semilla=0):
rnd, out, nueva = random.Random(semilla), [], 10**6
while len(out) < n:
out += [rnd.randrange(k - 1) for _ in range(2 * k)] # conjunto caliente de k - 1 páginas
out += list(range(nueva, nueva + k)) # escaneo de k páginas que no vuelven
nueva += k
return out[:n]
def traza_uniforme(n, paginas, semilla=0):
rnd = random.Random(semilla)
return [rnd.randrange(paginas) for _ in range(n)]
def traza_matmul(N, pagina, orden):
"""Páginas de A y B que lee C = A B con N x N doubles por filas y `pagina` doubles por página."""
pag = lambda m, i, j: (m, (i * N + j) // pagina)
out = []
for i in range(N):
for u in range(N):
for v in range(N):
kk, j = (v, u) if orden == "ijk" else (u, v) # ijk: el bucle interno recorre B por columnas
out += [pag("A", i, kk), pag("B", kk, j)]
return out
k, n = 8, 4000
trazas = {
"bucle de k+1": traza_bucle(n, k),
"Zipf, 64 páginas": traza_zipf(n, 64),
"caliente + escaneos": traza_escaneo(n, k),
"uniforme, 16 págs.": traza_uniforme(n, 16),
"matmul ijk": traza_matmul(16, 4, "ijk"),
"matmul ikj": traza_matmul(16, 4, "ikj"),
}
print(f"k = {k}. Fallos y, entre paréntesis, cociente con Belady\n")
print(f"{'traza':20s}{'accesos':>8}" + "".join(f"{p:>14s}" for p in POLITICAS))
for nombre, tr in trazas.items():
res = {p: f(tr, k) for p, f in POLITICAS.items()}
print(f"{nombre:20s}{len(tr):>8}" + "".join(f"{v:>7d} ({v / res['Belady']:4.2f})" for v in res.values()))
H8 = sum(1 / i for i in range(1, k + 1))
print(f"\ncotas del peor caso: LRU y FIFO {k}, marcado 2H_k = {2 * H8:.2f}")The table summarizes the lesson. On the loop, LRU, FIFO and LFU fault on all 4000 requests, times Belady (almost bound ), and marking stays at , nearly . With scans, LFU ties Belady and LRU pays times more. On the uniform trace all online policies are near 2: structureless traces do not distinguish them. In matrix multiplication, ikj order, traversing row-wise, cuts LRU faults from 5120 to 1088, while LFU collapses at times optimum: pages accumulate uses and LFU clings to them after they stop being used. Loop order matters more than policy, the topic of external memory.
Now check three theoretical bounds: Yao with uniform requests over pages, marking on the loop, and resource augmentation.
H = lambda k: sum(1 / i for i in range(1, k + 1))
print("Peticiones uniformes sobre k + 1 páginas, n = 20000")
print(f"{'k':>3} {'LRU/n':>8} {'1/(k+1)':>8} {'Belady/n':>9} {'1/((k+1)H_k)':>13} {'LRU/Belady':>11} {'H_k':>6}")
for k in (2, 4, 8, 16):
tr = traza_uniforme(20000, k + 1, semilla=k)
lru, opt = fallos_lru(tr, k), fallos_belady(tr, k)
print(f"{k:>3} {lru / 20000:>8.4f} {1 / (k + 1):>8.4f} {opt / 20000:>9.4f} {1 / ((k + 1) * H(k)):>13.4f} {lru / opt:>11.2f} {H(k):>6.2f}")
print("\nMarcado aleatorio en el bucle de k + 1 páginas (n = 8000, media de 10 semillas)")
for k in (2, 4, 8, 16):
tr = traza_bucle(8000, k)
m = sum(fallos_marcado(tr, k, s) for s in range(10)) / 10
print(f"k = {k:>2}: marcado / Belady = {m / fallos_belady(tr, k):.2f} H_k = {H(k):.2f} 2H_k = {2 * H(k):.2f}")
print("\nAumento de recursos: LRU con caché k en su traza adversaria, Belady con caché h")
for k, h in ((8, 8), (8, 6), (8, 4), (16, 8)):
tr = traza_bucle(4000, k)
print(f"k = {k:>2}, h = {h}: LRU / Belady = {fallos_lru(tr, k) / fallos_belady(tr, h):5.2f} cota k/(k-h+1) = {k / (k - h + 1):.2f}")With uniform requests, LRU faults on fraction , like any deterministic algorithm, and Belady on as coupon collection predicts: ratio approaches , Yao’s lower bound. Marking on the loop also approaches (with convergence is slower because startup faults weigh more). Resource augmentation reaches bound : the loop is worst case there too.
Lab 2: rent or buy
import numpy as np
def coste(k, D, B):
"""Alquila los días 1..k-1 y compra al empezar el día k."""
return D if D < k else k - 1 + B
def peor_cociente(k, B, Dmax=1000):
return max(coste(k, D, B) / min(D, B) for D in range(1, Dmax + 1))
B = 10
print("Deterministas, B = 10:")
for k in (1, 5, 9, 10, 11, 15, 20):
print(f" comprar el día {k:>2}: peor cociente {peor_cociente(k, B):.3f}")
print(f" 2 - 1/B = {2 - 1 / B}")
def dist_optima(B):
c = 1 / (1 - (1 - 1 / B) ** B)
return c, np.array([(c / B) * (1 - 1 / B) ** (B - i) for i in range(1, B + 1)])
c, p = dist_optima(B)
dias = np.arange(1, B + 1)
esperado = lambda p, D: sum(pi * coste(i, D, B) for i, pi in zip(dias, p))
print(f"\nAleatorizada óptima, B = 10: c_B = {c:.4f}, suma de p = {p.sum():.12f}")
print(" E[ALG]/OPT para D = 1..15:", np.round([esperado(p, D) / min(D, B) for D in range(1, 16)], 4))
u = np.full(B, 1 / B)
print(" uniforme, E[ALG]/OPT para D = 1..5:", np.round([esperado(u, D) / min(D, B) for D in range(1, 6)], 3))
# versión continua: comprar en T con densidad e^(t/B) / (B (e - 1)) en [0, B], muestreada por inversión
rng = np.random.default_rng(0)
Bc = 1.0
T = Bc * np.log1p(rng.random(400_000) * (np.e - 1))
print(f"\nContinua (Monte Carlo, 400 000 muestras): e/(e-1) = {np.e / (np.e - 1):.4f}")
for y in (0.1, 0.3, 0.6, 1.0, 2.0):
alg = np.where(T < y, T + Bc, y).mean()
print(f" temporada y = {y}: E[ALG]/OPT = {alg / min(y, Bc):.4f}")Worst deterministic ratio is V-shaped with minimum at ; optimal distribution gives for all durations simultaneously, and uniform starts at with . To see is best possible, solve the whole game. Rows are purchase days (the last acts as “never buy” within the horizon), columns durations , and entry ratio . The designer minimizes the column maximum using a mixed strategy, a linear program, and the dual gives the adversary’s mixed strategy.
import numpy as np
from scipy.optimize import linprog
B, N = 10, 60
K, Ds = np.arange(1, N + 2), np.arange(1, N + 1)
M = np.array([[coste(k, D, B) / min(D, B) for D in Ds] for k in K]) # filas: algoritmo; columnas: entrada
nk, nd = M.shape
# diseñador: min v sujeto a p^T M[:, D] <= v para toda D, p >= 0, sum p = 1
r = linprog(np.r_[np.zeros(nk), 1], A_ub=np.c_[M.T, -np.ones(nd)], b_ub=np.zeros(nd),
A_eq=[np.r_[np.ones(nk), 0]], b_eq=[1], bounds=[(0, None)] * nk + [(None, None)], method="highs")
p = r.x[:-1]
print(f"valor del juego (diseñador): {r.x[-1]:.6f} c_B = {1 / (1 - 0.9**10):.6f}")
print("días con probabilidad > 0:", K[p > 1e-9])
print("p del LP: ", np.round(p[:B], 4))
print("p de la fórmula:", np.round(dist_optima(B)[1], 4))
# adversario: max w sujeto a M[k, :] q >= w para todo k, q >= 0, sum q = 1
r2 = linprog(np.r_[np.zeros(nd), -1], A_ub=np.c_[-M, np.ones(nk)], b_ub=np.zeros(nk),
A_eq=[np.r_[np.ones(nd), 0]], b_eq=[1], bounds=[(0, None)] * nd + [(None, None)], method="highs")
q = r2.x[:-1]
print(f"\nvalor del juego (adversario): {-r2.fun:.6f}")
print("distribución de la duración:", {int(D): round(float(v), 4) for D, v in zip(Ds, q) if v > 1e-9})
print(f"Yao: mejor determinista contra q -> {(M @ q).min():.6f}, alcanzado por los días {K[np.isclose(M @ q, (M @ q).min())][:12]}")Both optimal strategies emerge from primal and dual with the same value. The designer’s matches the exponential formula. The adversary’s is a duration distribution against which every deterministic purchase day has expected ratio at least : exactly Yao’s certificate. Here the bound is on expectation of the ratio rather than ratio of expectations; since is fixed per column, both forms are equivalent by reweighting by . The adversary distribution is not unique (the LP returns one of many), but its value is.
The professional version
Python provides two ready-made pieces. functools.lru_cache memoizes a function with LRU eviction (CPython implements it in C over a dictionary and circular doubly linked list), and OrderedDict offers move_to_end and popitem(last=False) in , enough for an LRU cache in ten lines. Check that lru_cache makes exactly our LRU faults:
from functools import lru_cache
from collections import OrderedDict
traza = traza_zipf(4000, 64, semilla=3)
for k in (4, 8, 16):
@lru_cache(maxsize=k)
def pagina(p):
return p # «traer la página»: solo se ejecuta en un fallo
for p in traza:
pagina(p)
info = pagina.cache_info()
print(f"k = {k:>2}: lru_cache {info.misses} fallos, {info.hits} aciertos; fallos_lru = {fallos_lru(traza, k)}")
class LRU(OrderedDict):
"""Caché LRU sobre OrderedDict: get y put en O(1)."""
def __init__(self, k):
super().__init__()
self.k = k
def get(self, clave, defecto=None):
if clave not in self:
return defecto
self.move_to_end(clave)
return self[clave]
def put(self, clave, valor):
self[clave] = valor
self.move_to_end(clave)
if len(self) > self.k:
self.popitem(last=False)
c = LRU(2)
c.put("a", 1); c.put("b", 2); c.get("a"); c.put("c", 3)
print("\nclaves tras a, b, get(a), c con k = 2:", list(c))Outside Python, real caches are seldom exact LRU. CPUs use cheap approximations (tree-bit pseudo-LRU per set) because maintaining exact hardware order is expensive; operating systems use CLOCK and variants; databases and CDNs add scan resistance (2Q, ARC, LRU-K), exactly the scan-trace weakness shown. In high-performance multithreaded caches the doubly linked list is a bottleneck because every hit modifies it, so CLOCK or sampling is used (Redis, for example, evicts the oldest-used key among a small random sample).
Toward the frontier: algorithms with predictions
Competitive analysis is pessimistic because it assumes no future knowledge. In practice a learned model can predict it reasonably well: season duration or when a page is next requested. Algorithms with predictions seek both consistency (with perfect prediction, ratio approaches 1) and robustness (with arbitrarily poor prediction, ratio remains bounded comparably to the best algorithm without predictions).
For ski rental, Purohit, Svitkina and Kumar (NeurIPS 2018) propose, with confidence parameter and predicted duration : if buy at the start of day ; if buy at the start of day . They prove ratio at most , with prediction error : -consistent and -robust. Small means high trust in the model; as approaches 1, both purchase days tend to and recover the classical prediction-ignoring strategy. For paging, Lykouris and Vassilvitskii (ICML 2018) modify marking to use predicted next use of each page: its ratio improves as prediction error falls and never exceeds , marking without predictions; blindly following an oracle can instead be very bad even when mean error is small.
The connection to machine learning goes further. Online learning and bandits compare with the best fixed expert in hindsight rather than offline optimum, bounding regret, a difference rather than a ratio. It is the same adversarial game with a different yardstick.
Common mistakes
Exercises
Step 1 of 3. How do you bound the ratio of strategy ?
Step 1 of 3. How often can LRU fault in a phase?
list.remove and pop(0) traverse the list on each access. Rewrite it so get(clave) (returns the value or None and marks the key most recent) and put(clave, valor) (inserts or updates; if full, evicts the least recent) perform a constant number of operations. You may use a dictionary with your own doubly linked list, or OrderedDict. Tests check behavior and count key comparisons per operation with .class LRU:
"""Caché LRU de capacidad k. Funciona, pero cada acceso cuesta O(k): arréglalo."""
def __init__(self, k):
self.k = k
self.orden = [] # claves, de la menos a la más reciente
self.datos = {}
def get(self, clave):
"""Devuelve el valor (o None si no está) y marca la clave como la más reciente."""
if clave not in self.datos:
return None
self.orden.remove(clave)
self.orden.append(clave)
return self.datos[clave]
def put(self, clave, valor):
"""Inserta o actualiza; si no cabe, desaloja la menos reciente."""
if clave in self.datos:
self.orden.remove(clave)
elif len(self.datos) == self.k:
del self.datos[self.orden.pop(0)]
self.orden.append(clave)
self.datos[clave] = valor
def __len__(self):
return len(self.datos)Summary
- An algorithm is -competitive if for every . With randomness it matters what the adversary sees: gains are against an oblivious adversary and disappear against an adaptive offline one.
- In ski rental, buying on day gives , the deterministic optimum; buying at a time with density equalizes ratios across durations and gives , also optimal.
- In paging, Belady (farthest in future) is offline optimum; LRU, FIFO and all conservative algorithms are -competitive and no deterministic algorithm improves it. LFU is not competitive.
- Randomized marking is -competitive, and Yao’s principle with uniform requests over pages shows no randomized algorithm beats . Yao is the easy half of von Neumann’s minimax theorem.
- With cache versus an optimum with cache , LRU is -competitive: twice the memory gives a guarantee below 2.
- An LRU cache is implemented in with a hash table and doubly linked list with sentinels (or
OrderedDictandfunctools.lru_cache), never withlist.remove.