Lesson 12 · Memory management

Optimal Page Replacement: The Benchmark

Evict the page whose next use lies furthest in the future. It takes the fewest faults any policy can, and it needs the one input no operating system has: the future.

Optimal Page Replacement: The Benchmark concept diagramA visual explanation of the layout and operations shown in this lesson.all frames full — which page is needed furthest ahead?future →0304232frame 0furthest ahead — evict3frame 1next use 2 steps on0frame 2next use 1 step onthe longest reach wins — and needing the future is exactly why OPT cannot be implemented
1

How OPT Picks a Victim

The optimal page replacement algorithm, called OPT, MIN or Belady's optimal algorithm, runs when a page fault needs a frame and every frame is taken. It looks ahead along the reference string, finds when each resident page will next be used, and evicts the one whose next use is furthest away.

A page that is never used again is the perfect victim: throwing it out can never cause a later fault. When two or more pages are dead, or tie on distance, any of them will do; the fault count is the same.

Why nothing beats it. Suppose some policy evicts page X while OPT would evict Y, and X is needed before Y. Changing that choice to Y, and adjusting the later choices to match, never adds a fault: X is needed first, so keeping X saves a fault at least as early as keeping Y could. Repeating the swap at every decision turns any policy into OPT without raising its count. That exchange argument is why OPT is the floor.

  • Rule: maximise the distance to the next use
  • A page with no next use is evicted first
  • Ties do not change the number of faults
2

Worked Example: 7 Faults in 3 Frames

The string is the one the LRU and FIFO lessons use, so the counts compare directly. At each fault with full frames, scan forward from the current position, note each resident page's next use, and evict the furthest.

Only t = 8 is a real trade-off. Every resident page is needed again, so OPT gives up page 0, needed last, and keeps 2 and 3, which turn into hits at t = 9 and t = 10. The other three evictions remove pages that never come back.

Total: 7 faults and 6 hits: 3 compulsory faults to fill memory plus 4 evictions. FIFO takes 10 on this string and LRU 9.

OPT on 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 with 3 frames
tRefFrames afterResultWhy this victim
177 – –faultfree frame
207 0 –faultfree frame
317 0 1faultfree frame
422 0 1evict 77 and 1 never return; 0 is next at t = 5
502 0 1hit
632 0 3evict 11 never returns
702 0 3hit
842 4 3evict 02 at t = 9, 3 at t = 10, 0 at t = 11
922 4 3hit
1032 4 3hit
1102 0 3evict 44 never returns
1232 0 3hit
1322 0 3hit
  • Count check: 3 compulsory + 4 replacements = 7
  • Three of the four victims were never used again
  • With 4 frames OPT takes 6 faults
3

Why No Operating System Can Run It

The obstacle is missing information, not engineering. When a fault happens, the rest of the reference string depends on branches the program has not taken yet and input it has not read. Two runs with the same past can need different victims.

Profiling does not fix this: a trace from yesterday's run describes yesterday's input. So real kernels use the past as a guess. LRU assumes recently used pages will be used again soon, and clock approximates LRU with one hardware bit per page.

Lookahead is possible where the whole sequence really is known in advance: a compiler deciding which register to spill, a database running a fixed query plan, or a simulator replaying a recorded trace. Those systems do use OPT-style choices.

To compute OPT on a trace, a single backward pass records each position's next use of the same page. A heap keyed on next use then finds the victim in O(log k) for k frames, so a trace of n references costs O(n log k). The simple scan in the code is O(n·k) per fault, fine for exam-sized strings.

  • The future depends on input not yet read
  • Real policies use recent past as the guess
  • Computable only when the full sequence is known in advance
Key reference

Terms, operations, and practical uses

The rule

  • DecisionEvict the resident page whose next use is furthest ahead.
  • Dead pageNever referenced again; evicting it costs nothing.
  • TiesPick any; the fault count is unchanged.
  • NamesOPT, MIN, or Belady's optimal algorithm.

Why it cannot ship

  • Missing inputThe future reference string does not exist at fault time.
  • ProfilesA different input takes different branches.
  • Offline useRun on a recorded trace to get the fault floor.
  • ExceptionsRegister spilling, fixed query plans, trace replay.

Numbers

  • 7 faultsOn 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames; 6 with 4 frames.
  • OthersFIFO 10, LRU 9, clock 9 on the same string.
  • Belady's stringOPT 7 then 6 as frames go 3 to 4; FIFO 9 then 10.
  • Cost offlineO(n log k) with next-use positions and a heap.
Implementation

OPT on 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames

def optimal(refs, frames):
    """Optimal page replacement. Returns (faults, hits).

    Evicts the resident page whose next use lies furthest ahead. Needs the
    whole reference string up front, which is why this is a benchmark rather
    than something an operating system can run.
    """
    resident, faults, hits = [], 0, 0

    for i, page in enumerate(refs):
        if page in resident:
            hits += 1
            continue

        faults += 1
        if len(resident) < frames:
            resident.append(page)
            continue

        # Distance to each resident page's next use; never used again wins.
        def next_use(candidate):
            future = refs[i + 1:]
            return future.index(candidate) if candidate in future else float("inf")

        victim = max(resident, key=next_use)
        resident[resident.index(victim)] = page

    return faults, hits


refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
faults, hits = optimal(refs, 3)
print(f"{faults} faults, {hits} hits")  # 7 faults, 6 hits
#include <algorithm>
#include <iostream>
#include <vector>

// Optimal page replacement: evict the page used furthest in the future.
// Returns the fault count; `hits` receives the hit count.
int optimal(const std::vector<int>& refs, int frames, int& hits) {
    std::vector<int> resident;
    int faults = 0;
    hits = 0;

    for (size_t i = 0; i < refs.size(); ++i) {
        int page = refs[i];
        if (std::find(resident.begin(), resident.end(), page) != resident.end()) {
            ++hits;
            continue;
        }

        ++faults;
        if (static_cast<int>(resident.size()) < frames) {
            resident.push_back(page);
            continue;
        }

        // Furthest next use, treating "never again" as infinitely far.
        size_t bestDistance = 0;
        size_t victimIndex = 0;
        for (size_t v = 0; v < resident.size(); ++v) {
            size_t distance = refs.size();
            for (size_t j = i + 1; j < refs.size(); ++j) {
                if (refs[j] == resident[v]) {
                    distance = j;
                    break;
                }
            }
            if (distance > bestDistance) {
                bestDistance = distance;
                victimIndex = v;
            }
        }
        resident[victimIndex] = page;
    }

    return faults;
}

int main() {
    std::vector<int> refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
    int hits = 0;
    int faults = optimal(refs, 3, hits);
    std::cout << faults << " faults, " << hits << " hits\n";  // 7 faults, 6 hits
    return 0;
}
import java.util.ArrayList;
import java.util.List;

public class Main {

    /** Evicts the resident page whose next use is furthest ahead. */
    static int[] optimal(int[] refs, int frames) {
        List<Integer> resident = new ArrayList<>();
        int faults = 0;
        int hits = 0;

        for (int i = 0; i < refs.length; i++) {
            int page = refs[i];
            if (resident.contains(page)) {
                hits++;
                continue;
            }

            faults++;
            if (resident.size() < frames) {
                resident.add(page);
                continue;
            }

            int victimIndex = 0;
            int bestDistance = -1;
            for (int v = 0; v < resident.size(); v++) {
                int distance = Integer.MAX_VALUE;
                for (int j = i + 1; j < refs.length; j++) {
                    if (refs[j] == resident.get(v)) {
                        distance = j;
                        break;
                    }
                }
                if (distance > bestDistance) {
                    bestDistance = distance;
                    victimIndex = v;
                }
            }
            resident.set(victimIndex, page);
        }

        return new int[] {faults, hits};
    }

    public static void main(String[] args) {
        int[] refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
        int[] result = optimal(refs, 3);
        System.out.println(result[0] + " faults, " + result[1] + " hits");
    }
}
Watch it run

Step through it

Running on refs 7,0,1,2,0,3,0,4,2,3,0,3,2 · 3 frames

OPT, 3 frames, future knownreference string7012030423032faults 0 · hits 0
Step 1

Three empty frames, 13 references

Memory holds three pages and the whole reference string is known in advance. That is the one thing OPT needs: on a fault with full frames, it looks ahead along the string and evicts the resident page whose next use is furthest away, or never comes.

Output
1 / 14
4

OPT as a Benchmark

Run OPT over a recorded trace and you get the lowest fault count that trace allows. A real policy is then judged by its distance from that floor, not by its raw count. LRU's 9 against OPT's 7 means at most two faults are left to win; a policy at 40 against 7 is broken.

OPT is also a stack algorithm: the pages it holds with k frames are always a subset of those it holds with k + 1. So adding memory never adds faults. On Belady's string 1,2,3,4,1,2,5,1,2,3,4,5, OPT takes 7 faults with three frames and 6 with four, while FIFO gets worse, going from 9 to 10.

Policies on 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames
AlgorithmFaultsVictimCan an OS run it?
OPT7Next use furthest aheadNo: needs the future
LRU9Last use furthest backOnly approximately
Clock9First page with reference bit 0Yes, cheaply
FIFO10Oldest arrivalYes, trivially
  • Gives the fault floor for a recorded trace
  • Tells you how much any real policy can still gain
  • Immune to Belady's anomaly