Online Problems and the Competitive Ratio
Every algorithm so far received its whole input before it started. Many real decisions are not like that. A cache must decide which page to evict now, without knowing the future requests; a scheduler must place a job when it arrives; a ski renter must decide each morning whether to buy. These are online problems: the input arrives piece by piece, and each decision is final. This lesson defines how to measure an online algorithm, the competitive ratio, and applies it to the most studied online problem, paging.
Online versus offline
An online algorithm receives a request sequence one request at a time and must serve before seeing . The offline optimum is the least cost of serving the whole sequence by someone who knows it in advance. No online algorithm can match OPT on every input, because OPT can tailor its choices to the future. The question is how much is lost.
An online algorithm ALG is -competitive if there is a constant such that for every request sequence
If this holds with , ALG is strictly -competitive. The smallest such is the competitive ratio of ALG. It is a worst-case measure over all inputs: think of an adversary who knows the algorithm and picks the sequence that hurts it most. For a deterministic algorithm the adversary can simulate it and always knows its next move; randomized algorithms are measured against an oblivious adversary who knows the algorithm but not its coin flips.
Paging
A cache holds pages of a larger set. Each request names a page; if the page is in the cache it is a hit (cost 0), otherwise a miss (cost 1): the page is loaded and, if the cache is full, some page must be evicted. The cost is the number of misses. Three eviction rules:
- LRU (least recently used): evict the page whose last request is oldest.
- FIFO (first in, first out): evict the page that was loaded earliest.
- OPT, Belady's rule: evict the page whose next request is furthest in the future (or never comes). It needs the future, so it is offline, and Belady proved in 1966 that it minimises the number of misses.
The animation runs LRU on twelve requests with three slots; switch to OPT by reading on.
The program serves the same requests with each rule and prints the same decisions as the animation (requests numbered from 1).
def serve(requests, k, policy):
cache, last_use, loaded, log, misses = [None] * k, {}, {}, [], 0
for t, page in enumerate(requests):
if page in cache:
log.append(f"{page}: hit")
else:
misses += 1
if None in cache:
slot = cache.index(None)
log.append(f"{page}: miss, free slot")
else:
if policy == "lru":
key = lambda i: last_use[cache[i]]
slot = min(range(k), key=key)
elif policy == "fifo":
slot = min(range(k), key=lambda i: loaded[cache[i]])
else: # opt: furthest next use
def next_use(i):
rest = requests[t + 1:]
return rest.index(cache[i]) if cache[i] in rest else len(requests)
slot = max(range(k), key=next_use) # first slot among ties
log.append(f"{page}: miss, evict {cache[slot]}")
cache[slot] = page
loaded[page] = t
last_use[page] = t
return misses, log
requests = list("ABCADBEACBDE")
for policy in ["lru", "fifo", "opt"]:
misses, log = serve(requests, 3, policy)
print(f"{policy.upper():4} {misses:2} misses:", "; ".join(log[3:]))LRU 11 misses: A: hit; D: miss, evict B; B: miss, evict C; E: miss, evict A; A: miss, evict D; C: miss, evict B; B: miss, evict E; D: miss, evict A; E: miss, evict C
FIFO 10 misses: A: hit; D: miss, evict A; B: hit; E: miss, evict B; A: miss, evict C; C: miss, evict D; B: miss, evict E; D: miss, evict A; E: miss, evict C
OPT 7 misses: A: hit; D: miss, evict C; B: hit; E: miss, evict D; A: hit; C: miss, evict A; B: hit; D: miss, evict C; E: hit
LRU misses 11 times and OPT only 7. The animation with "policy": "opt" shows Belady's choices:
LRU is -competitive
Theorem (Sleator and Tarjan, 1985). LRU and FIFO are -competitive for paging with a cache of pages.
Proof sketch for LRU
Cut the request sequence into phases: phase 1 starts at the first request, and each phase is the longest stretch that requests at most distinct pages; the next request (a -st distinct page) starts the next phase.
LRU misses at most times per phase. Once a page is requested within a phase, it is among the most recently used pages for the rest of that phase (only distinct pages are requested in it), so LRU never evicts it before the phase ends. Each of the at most distinct pages of the phase can therefore miss at most once.
OPT misses at least once per phase after the first. Take phase and let be its first request. From the second request of phase to the first request of phase inclusive, at least distinct pages other than are requested. Right after serving , OPT holds and only other pages, so it misses at least once in that window. The windows of different phases are disjoint.
So with phases, and , which gives .
No deterministic algorithm does better
The matching lower bound is a pure adversary argument. Use only distinct pages. After the cache fills, exactly one of them is missing from the cache at any time, and the adversary always requests that page. Every request is a miss for the online algorithm. OPT, facing the same sequence, evicts the page whose next request is furthest away; at least other requests come before that page is needed again, so OPT misses at most once every requests.
def opt_misses(requests, k):
cache, misses = set(), 0
for t, page in enumerate(requests):
if page in cache:
continue
misses += 1
if len(cache) == k:
rest = requests[t + 1:]
far = max(cache, key=lambda p: rest.index(p) if p in rest else len(rest))
cache.remove(far)
cache.add(page)
return misses
def adversary(evict, k, length):
"""build the worst sequence for a deterministic eviction rule over k + 1 pages"""
pages = list(range(k + 1))
cache, requests = list(range(k)), list(range(k))
for t in range(length):
page = next(p for p in pages if p not in cache) # the one page not cached
requests.append(page)
victim = evict(cache, requests)
cache[cache.index(victim)] = page
return requests
def lru(cache, requests): # least recently used, before the new request
past = requests[:-1]
return min(cache, key=lambda p: max(i for i, q in enumerate(past) if q == p))
def mru(cache, requests): # most recently used, before the new request
past = requests[:-1]
return max(cache, key=lambda p: max(i for i, q in enumerate(past) if q == p))
for k in [2, 4, 8]:
for name, rule in [("LRU", lru), ("MRU", mru)]:
seq = adversary(rule, k, 240)
alg = 240 + k # every request misses (k cold misses first)
opt = opt_misses(seq, k)
print(f"k = {k}, {name:6}: ALG {alg} misses, OPT {opt:3}, ratio {alg / opt:.2f}")k = 2, LRU : ALG 242 misses, OPT 122, ratio 1.98
k = 2, MRU : ALG 242 misses, OPT 3, ratio 80.67
k = 4, LRU : ALG 244 misses, OPT 64, ratio 3.81
k = 4, MRU : ALG 244 misses, OPT 5, ratio 48.80
k = 8, LRU : ALG 248 misses, OPT 38, ratio 6.53
k = 8, MRU : ALG 248 misses, OPT 9, ratio 27.56
Against LRU the ratio approaches as the sequence grows (OPT's cold misses still weigh on the short run for ). Evicting the most recently used page is far worse: the adversary just alternates between two pages, which OPT keeps in the cache. Whatever deterministic rule the cache uses, the ratio is at least about . Randomization helps: the marking algorithm, which evicts a random page among those not requested recently, is -competitive against an oblivious adversary (), exponentially better than . That and much more is in the Part II course Online Algorithms & Competitive Analysis.
In C++
LRU and OPT in C++ on a longer request sequence with locality (a fixed pseudo-random walk over 12 pages), for several cache sizes. Unlike the adversarial sequences, a trace with locality gives LRU ratios far below .
#include <algorithm>
#include <cstdio>
#include <vector>
int lru(const std::vector<int>& req, int k) {
std::vector<int> cache; // front = least recently used
int misses = 0;
for (int p : req) {
auto it = std::find(cache.begin(), cache.end(), p);
if (it != cache.end()) cache.erase(it);
else { misses++; if ((int)cache.size() == k) cache.erase(cache.begin()); }
cache.push_back(p);
}
return misses;
}
int opt(const std::vector<int>& req, int k) {
std::vector<int> cache;
int misses = 0;
for (size_t t = 0; t < req.size(); t++) {
if (std::find(cache.begin(), cache.end(), req[t]) != cache.end()) continue;
misses++;
if ((int)cache.size() == k) {
size_t best = 0, far = 0;
for (size_t i = 0; i < cache.size(); i++) {
size_t next = t + 1;
while (next < req.size() && req[next] != cache[i]) next++;
if (next > far) { far = next; best = i; }
}
cache.erase(cache.begin() + best);
}
cache.push_back(req[t]);
}
return misses;
}
int main() {
std::vector<int> req;
unsigned x = 12345;
int page = 0;
for (int t = 0; t < 2000; t++) { // a fixed walk: mostly nearby pages
x = x * 1103515245u + 12345u;
int step = int((x >> 16) % 5) - 2;
page = (page + step + 12) % 12;
req.push_back(page);
}
std::printf(" k LRU OPT ratio\n");
for (int k : {2, 3, 4, 6, 8})
std::printf("%2d %5d %5d %.2f\n", k, lru(req, k), opt(req, k), (double)lru(req, k) / opt(req, k));
} k LRU OPT ratio
2 1159 988 1.17
3 903 726 1.24
4 755 562 1.34
6 558 343 1.63
8 401 191 2.10
The gap between the worst case and these ratios is typical of competitive analysis: it guards against every input, so it can be pessimistic for the inputs that actually occur. It still says something real: no deterministic rule is safe against a request pattern that cycles through just one page more than the cache holds, and LRU's behaviour on loops larger than the cache is a well-known performance cliff. The Page Replacement lesson of the Operating Systems course shows how real kernels approximate LRU. Practise with Count Cache Misses.
Test yourself
An online algorithm is -competitive if, for every request sequence ,
- for a constant
- the average cost over random sequences is at most
With a cache of pages, which request pattern forces every deterministic paging algorithm to miss on every request?
- Requests for distinct pages in a cycle
- Always requesting the one page, out of , that is not in the cache
- Requests in sorted order
- Random requests
On the requests A B C A D B E A C B D E with 3 slots, how many misses does OPT have?
- 5
- 7
- 9
- 11
What does Belady's rule evict?
- The least recently used page
- The page loaded first
- The page whose next request is furthest in the future
- A random page