Caching policies (LRU, FIFO, furthest-in-future)
Three caches of the same size serve one request sequence and their misses are compared; furthest-in-future is optimal but has to know the future.
A cache is small and fast and holds only k items. A request for an item not in it is a miss: the item must be
brought in, and if the cache is full, one item has to go. Which one?
- Time:
O(n·k) (furthest-in-future: O(n²·k) here) - Space:
O(k) - CLRS, section 15.4
- CLRS, section 27.3
A cache of 3 and 12 requests; misses: LRU 10, FIFO 9 and the optimum 7.
def caching(R, k):# Three caches of size k serve the same requests: LRU, FIFO and furthest-in-future (the offline optimum).reqs = R[0]lru = [] # least recently used firstfifo = [] # oldest firstopt = []hits = [0, 0, 0]misses = [0, 0, 0]rows = [] # for the picture: each request and the three caches after itfor t in range(len(reqs)):x = reqs[t]if x in lru:hits[0] = hits[0] + 1lru.remove(x)lru.append(x)else:misses[0] = misses[0] + 1if len(lru) == k:y = lru.pop(0)lru.append(x)if x in fifo:hits[1] = hits[1] + 1else:misses[1] = misses[1] + 1if len(fifo) == k:y = fifo.pop(0)fifo.append(x)if x in opt:hits[2] = hits[2] + 1else:misses[2] = misses[2] + 1if len(opt) == k:y = furthest(reqs, t, opt)opt.remove(y)opt.append(x)rows.append([x, list(lru), list(fifo), list(opt)])return missesdef furthest(reqs, t, cache):# The cached item whose next request is furthest away (or never comes).best = cache[0]best_next = -1for y in cache:nxt = len(reqs)for s in range(len(reqs) - 1, t, -1):if reqs[s] == y:nxt = sif nxt > best_next:best = ybest_next = nxtreturn best
Start
The table is still empty.
Local variables
Orange = changed in this step
R list
Call stack
- caching()line 1
Explanation
The problem
A cache is small and fast and holds only k items. A request for an item not in it is a miss: the item must be
brought in, and if the cache is full, one item has to go. Which one?
- LRU: the item whose last use is longest ago.
- FIFO: the item that came in first.
- Furthest-in-future (Belady): the item whose next request comes latest.
Why furthest-in-future is optimal
An exchange argument (the greedy-algorithms chapter of CLRS) shows that any optimal schedule can be turned, step by step, into this greedy choice without adding misses. But the policy is offline: it has to know the future.
Online policies
LRU and FIFO do not know the future. Both are k-competitive: their misses are at most about k times the
optimum's, and no deterministic online algorithm can do better (CLRS chapter 27).
The input
R is the requests and k the cache size.