Every line of code you write is full of if-statements. Every time the CPU hits one, it faces a fork in the road: take the branch, or skip it? The answer depends on data that hasn't been computed yet.
A naive processor would stall — freeze the pipeline, wait for the result, then continue. On a modern chip running four instructions per clock, that stall costs 10–20 cycles of wasted work. In a tight loop that runs a billion times, a few stalled cycles per iteration adds up to seconds of lost time.
The solution is branch prediction: the CPU guesses the outcome before computing it, speculatively executes the most-likely path, and discards the work if it guessed wrong. A good predictor is right more than 99% of the time, turning a potential 15-cycle penalty into a 0-cycle non-event.
Understanding branch prediction means understanding why sorting a list makes it faster to search, why Spectre and Meltdown were possible, and why a single mispredict can cost more than hundreds of correct predictions combined.
Comments
Loading comments...