BRANCH PREDICTION

Sorted data runs faster through the same loop

L215 MINSYSTEMS & LOW-LEVEL
PREDICT

The loop runs over 256 bytes and branches on each one (add it if it is 128 or more). The CPU guesses each branch before it knows the answer. Sorted, the loop takes 286 cycles. Each wrong guess (a mispredict) costs 15 cycles. Roughly how many cycles does it take when the bytes are in random order?

A pipelined CPU fetches instructions before it knows where a branch goes. It has to guess. The simplest predictor, and the one simulated here, keeps a small counter per branch: two bits, 0 to 3. Each taken branch moves it up, each not-taken one moves it down, and it saturates at both ends. Values 2 and 3 predict taken. Real cores add branch history (TAGE, perceptron predictors), but none of them can learn random data either.

A right guess is free. A wrong guess flushes every instruction fetched down the wrong path, about 15 cycles here. Sorted data sends the branch one way for 128 iterations, then the other way: two misses in total. Random data gives the counter nothing to learn.

▶ SIMULATION
CPU (in-order pipeline)
i = 0 / 256 · sum = 0
cycles 0 · flushed 0
—
PREDICTOR (2-bit counter)
counter = 1 (weakly not taken)
next prediction: not taken
DATA (—)
next: —
noise n/a
branches on x0
mispredicts0 (0.0%)
cycles per element—
✓ mispredict rate ≤ 5% of data-dependent branches
SCHEDULE
01[DATA]sort the 256 bytes, then run the loop
02[CPU]iterations 0–31
03[CPU]iterations 32–63
04[CPU]iterations 64–95
05[CPU]iterations 96–127
06[CPU]iterations 128–159
07[CPU]iterations 160–191
08[CPU]iterations 192–223
09[CPU]iterations 224–255
10[CPU]report cycles
Start of sorted data scenario. 10 steps.
long sum = 0;
for (int i = 0; i < n; i++)
    if (data[i] >= 128)      // a conditional jump on data the predictor cannot guess
        sum += data[i];

Watch the mispredict row and the invariant strip. RANDOM DATA crosses 5% in the first chunk and ends with most of its cycles spent on flushes. SORTED DATA misses twice, at the 128 boundary. BRANCHLESS runs the same random bytes with no branch on x at all: 512 cycles, whatever the order.

TUNE IT NOT YET

Sorted data keeps the predictor almost perfect. Real data is rarely perfectly sorted. Raise NOISE (the percent of elements replaced with random bytes) and find the smallest noise level at which the mispredict rate goes over 5%.

GOAL: mispredict rate > 5% at this noise, ≤ 5% at every lower noise

FIX IT NOT YET

Implement the 2-bit saturating counter. update(state, taken) takes the counter (0..3) and the real outcome and returns the next counter. 0 and 1 predict not taken, 2 and 3 predict taken. The grader checks every transition and then runs it on a loop branch that is taken 7 times and falls through once, repeated.

Mental model:

a branch is a bet the CPU places before it knows the answer. It costs nothing when the bet is predictable and a whole pipeline flush when it is not. Performance depends on the pattern in your data, not only on the instruction count. When the pattern is noise, take the bet away: make the code branchless and pay a small, fixed cost every time.

IN PRODUCTION

Hot loops that filter, clamp, or bucket values: parsers, compression, query engines scanning columns, sorting networks. Profilers show it as a high branch-misses count in perf stat. The fixes you will see are sorting or partitioning first, cmov and SIMD masks, and likely/unlikely hints for branches that are rarely taken.

IN INTERVIEWS

“Why is processing a sorted array faster?” Explain pipelining, prediction and the flush penalty. Say how a 2-bit counter behaves on sorted versus random input, then give the branchless rewrite and say when it loses (when the branch was already predictable).

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: FALSE SHARING →