intermediate

Sorting the Input Made the Loop Faster

Read the counters before the options. Nothing here is labelled with the answer.

The report

A colleague claims that sorting our data before the filter loop makes the loop three times faster, even counting the sort. That makes no sense — sorting is strictly more work and the loop does exactly the same comparisons either way. One of us is measuring wrong.

The filter loop, unchanged; only the input order differs
total = 0
for i in 0 .. n-1:
    if data[i] >= threshold:      // ~50% of elements pass
        total += data[i]
CountersSIMULATED
instructionsunsorted 1.00×, sorted 0.97×Both runs retire essentially the same number of instructions.
cyclesunsorted 3.2× sortedThe unsorted run takes over three times as many cycles for the same instructions.
branch-instructionsidentical in both runsThe same number of branches is executed either way.
branch-missesunsorted 48.7% of branches, sorted 0.1%Almost half the branches are mispredicted in one run and almost none in the other.
L1-dcache-load-misses1.9% in both runsCache behaviour is the same in both runs.
IPCunsorted 0.61, sorted 1.98Per-cycle progress is roughly three times better in the sorted run.
What is the hardware doing?