← engineering lobe

Branch prediction: how your CPU guesses the future

2026-12-036 min read#deep-tech#hardware#cpu#performance

Take this loop:

for (int i = 0; i < n; i++)
    if (data[i] >= 128)
        sum += data[i];

Run it on an array, then on the same array sorted. Same numbers, same work. Yet the sorted one runs faster. Why is a well-known Stack Overflow question 1.

The answer is a part of the CPU that guesses which way every if will go, before it knows. In this article, let’s see why it has to guess, and how it gets so good at it.

Problem

A CPU doesn’t run one instruction at a time. It works like an assembly line: while one instruction executes, the next ones are already being fetched and decoded 2. A modern core has a long line, so many instructions are in flight at once.

Branches break this. The CPU only knows which way an if goes when the comparison actually executes, deep in the line. Until then, it doesn’t know what to fetch next. Waiting would leave most of the line empty.

So it guesses. It picks the more likely side and starts running it speculatively: the results are kept aside until the branch is checked 2. If the guess was right, nothing was lost. If it was wrong, everything fetched after the branch is thrown away, and the line starts again from the right place. That’s a branch misprediction, and “the number of wasted clock cycles is approximately equal to the length of the pipeline” 2. Agner Fog’s guide gives 15 to 18 cycles for AMD Zen 4, and 15 to 25 for Zen 5 2.

Here is the loop above on a toy 8-stage line that checks the branch in stage 6. Run it on sorted data, then on random data:

for x in data: if x >= 128: sum += x
?7 checks x[7] ≥ 128+7 adds x[7]thrown away
elements done
wrong guesses
cycles per element

To give you a summary:

  1. With sorted data, the branch goes “not taken” for the first half and “taken” for the second. The CPU only guesses wrong a few times: while it warms up, and at the switch.
  2. With random data, it’s wrong about half the time. Each wrong guess throws away the work in flight.

So how does the CPU make its guess?

Same as last time

The simplest idea: remember what each branch did the last time, and guess that. One bit per branch.

That’s fine for a branch that always goes the same way. But think of a loop that runs 4 times, over and over. Its branch goes T, T, T, N (taken three times, then not taken on the exit). The one-bit guess is wrong at the exit, and then wrong again on the first round of the next loop, because the last thing it saw was N. Two misses per loop.

The 2-bit counter

The fix is to require two surprises before changing your mind. Each branch gets a small counter with four states 2 3:

  1. Taken moves it one step up, not taken one step down. It stops at the ends.
  2. The upper two states predict taken, the lower two predict not taken.

One unusual outcome only moves it from “strongly taken” to “weakly taken”, so the next guess is still taken. Try it:

a 2-bit saturating counter

McFarling’s 1993 paper calls this bimodal prediction, since most branches are either “usually taken or usually not taken”. On the SPEC’89 benchmarks, it gets 93.5% right once every branch has its own counter 3.

93.5% sounds great until you remember each miss costs 15 or more cycles. And there’s a pattern the counter can’t handle at all.

Learning patterns

Take a branch that alternates: T, N, T, N. The counter just bounces between two neighbouring states. Agner Fog’s guide walks through it: depending on where it starts, it’s right 50% of the time, or in the worst case, wrong every single time 2.

The fix, from T.-Y. Yeh and Y. N. Patt, is to also remember the branch’s last few outcomes, and keep a separate counter for each possible history 2. With 2 bits of history, the alternating branch only ever has history 01 or 10. The counter for 01 learns that a T comes next, and the counter for 10 learns that an N comes next. After a short warm-up, it’s right every time.

Agner’s rule for how far this goes: with n bits of history, “any repetitive pattern with a period of n+1 or less can be predicted perfectly after a warm-up time no longer than three periods” 2.

Here are the four predictors so far, on the same branch. The last one uses 4 bits of history:

four predictors, one branch · last 40 guesses shown

Notice two things:

  1. On TTNN, the plain 2-bit counter does worse than always guessing taken. History gets it to nearly 100%.
  2. The loop of 8 has a period of 8, more than 4 + 1. Four Ts in a row can be followed by a T or an N, so the history predictor is no better than the counter there. Exactly what the rule says.

Global history

So far each branch only looks at its own past. But branches are related. If one if (x > 0) was taken, a later if (x > 5) tells you something too.

So real predictors also keep a global history: the outcomes of the last n branches, whichever branches they were. “Many modern processors use variants of this method with values of n from 8 to 16” 2.

Sharing one table across all branches has a problem: two unrelated branches with the same recent history land on the same counter and confuse each other. McFarling’s fix is to mix the branch’s address into the index, with an XOR of the address and the global history. He called it gshare 3. The same paper also combines two predictors and keeps a third table that learns, per branch, which of the two to trust. That got 98.1% right, against 97.1% for the best design before it 3.

What today’s CPUs do exactly isn’t public. Even Agner, after measuring Zen 5, writes “I am not able to verify what goes on under the hood” 2. But they are built from these same ideas: counters, history, and tables indexed by both.

Random is random

No predictor can guess a coin flip. Agner’s table for a random branch: with a 50/50 split, half the guesses are wrong 2. More history doesn’t help, there is nothing to learn.

That’s the sorted array question. The loop is identical. Sorting just turns a random branch into a boring one.

If you can’t sort, you can sometimes remove the branch:

int mask = -(data[i] >= 128);   // all 1s or all 0s
sum += data[i] & mask;

Now there’s nothing to guess. It’s not free though. Agner’s guide gives this advice for the Pentium 4, with the catch to use it only if it doesn’t add “costly extra dependences and latency” 2. Measure before you trust it.

Final Thoughts

A few limits worth knowing:

  1. Prediction only works on patterns. A branch on random data is wrong half the time, whatever the hardware.
  2. The longer the pipeline, the more a miss costs 2.
  3. The tables are finite. With too little space, branches share counters and accuracy drops 3.
  4. Guessing leaves traces. Spectre showed that an attacker can train the predictor so the CPU speculatively runs code it should never run, and leaks secrets through a side channel 4.

So next time your code is slow for no reason, look for an if on data that looks like noise.

Footnotes

  1. Stack Overflow, Why is processing a sorted array faster than processing an unsorted array? ↩

  2. Agner Fog, The microarchitecture of Intel, AMD and VIA CPUs. Pipelines, speculation, saturating counters, two-level and global predictors, and Table 3.1 (random branches) in section 3 and 3.1; Zen 4 and Zen 5 penalties in 3.13; the conditional move advice in 5.13. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12 ↩13

  3. Scott McFarling, Combining Branch Predictors, DEC WRL Technical Note TN-36, 1993. Bimodal prediction in section 3, gshare in section 7, combining in section 8 and its accuracy in the abstract. ↩ ↩2 ↩3 ↩4 ↩5

  4. Paul Kocher et al., Spectre Attacks: Exploiting Speculative Execution, IEEE Symposium on Security and Privacy, 2019. ↩

Connected thoughts

neurons this one fires into: shared ideas first, then neighbours in time.