Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Guide

How Branch Prediction and Branchless Programming optimize hot loops in C++ [StackOverflow Architecture Guide]

assembly_micro_dev
x86_64 Micro-arch
MEMBER
Rozpustnik: 186
Data dołączenia: Oct 2021
Posty: 10
Dzięki: 27
1 miesięcy temu · Jul 25, 2026 6:54 AM
#1

Why sorted arrays process 6x faster than unsorted arrays in conditional loops:

CPU branch predictors use historical pattern history tables to speculate which branch will be taken. Random unsorted data causes constant branch mispredictions, flushing the 14-20 stage CPU execution pipeline (costing 15-20 wasted clock cycles per branch!).

Branchless Clamp in C++:

CPP
// Branching (Misprediction risk)
int ClampBranch(int v, int minV, int maxV) {
    if (v < minV) return minV;
    if (v > maxV) return maxV;
    return v;
}

// Branchless using CMOV (Conditional Move)
int ClampBranchless(int v, int minV, int maxV) {
    v = (v < minV) ? minV : v;
    v = (v > maxV) ? maxV : v;
    return v; // Compiles directly to x86 'cmovl' and 'cmovg' instructions with 0 branches!
}
profiler_pat
Performance Hunter
MEMBER
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
4 tygodnie temu · Jul 25, 2026 11:34 AM
#2

The cmov instruction completely eliminates branch mispredictions in hot physics and financial calculation loops.

simd_vector_ace
SIMD & Intrinsics
MEMBER
Rozpustnik: 151
Data dołączenia: May 2020
Posty: 8
Dzięki: 36
4 tygodnie temu · Jul 26, 2026 2:07 AM
#3

Profiling with perf stat -e branch-misses ./app is the gold standard for identifying branch prediction bottlenecks.