Kayavak

Kayavak / Work backwards

Work backwards

Sorting the data made the loop 7 times faster

The same loop over the same million bytes ran 7.3 times faster once the bytes were sorted, and only 30% faster when the compiler was left alone.

The result

Volume 1's hardware lab added up the bytes ≥ 128 in a million random bytes, then did the same after sorting them. With the program compiled normally, sorted was about 30% faster. With the compiler told not to turn the if into branch-free code, the unsorted run was 7.3 times slower than the sorted one (the lab).

The work is identical: the same comparisons and additions. Only the order changed.

Work back from it

First question: what in a CPU could care about the *order* of data rather than its amount?

Anything that predicts. Caches predict which data you'll want; the branch predictor predicts which way each if will go. Here the data is a million bytes read in order either way, so suspect the if.

Step 1: why does a CPU predict branches at all?

A modern core works on many instructions at once in a pipeline. At an if it doesn't yet know the outcome, so rather than stall it guesses and carries on speculatively (branch prediction).

Step 2: what does a wrong guess cost, and how often is the guess wrong here?

The speculative work is thrown away and the pipeline refilled, about 15–20 cycles. On random bytes, "≥ 128" is true half the time with no pattern, so the predictor is wrong about half the time. Sorted, it's "no" for the first half and "yes" for the second: almost always right.

Step 3: then why was the normally compiled version only 30% apart?

The compiler removed the branch. Its output used a conditional move (cmovg): compute both outcomes and pick one, with no jump to predict. With nothing to mispredict, order hardly matters.

The root cause

A data-dependent branch that the predictor can't learn costs a pipeline flush about half the time. Sorting made the branch predictable; the compiler's branch-free code made prediction unnecessary.

What follows from it

Recall

Why does random data make `if (x >= 128)` slow?

The predictor can't learn a pattern, guesses wrong about half the time, and each miss flushes the pipeline (about 15–20 cycles).

How did the compiler make order nearly irrelevant?

It replaced the branch with a conditional move, so there was nothing to predict.