BRANCH PREDICTION
Sorted data runs faster through the same loop
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.
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];// Option 1: sort first, so the branch is a run of not-taken then a run of taken.
std::sort(data, data + n);
// Option 2: no branch at all. -(x >= 128) is all ones or all zeros.
for (int i = 0; i < n; i++)
sum += data[i] & -(data[i] >= 128); // compilers often emit cmov for this 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.
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
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.
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.
“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).