An instruction’s cost is determined not by its byte length or line count in a listing, but by what it does to the pipeline: stalling on a data dependency, mispredicting a branch, or avoiding both.
We’ve seen the decisions the compiler makes on your behalf. The next step is measuring their real cost on the same array. On a Ryzen 7 7840H testbed, two equally valid implementations of finding a maximum differ by 6x in runtime, and perf stat proves the gap has nothing to do with instruction count.
Mental Model: What Actually Costs a Cycle
| Intuition | What the testbed shows |
|---|---|
| Fewer instructions means faster code | Inside the loop body, the cmov version is even shorter than the branchy one (6 instructions vs. 7), yet on sorted data the branch is 2x faster—and on unpredictable data it’s 6x slower |
cmov always beats a branch |
On predictable data, cmov is twice as slow |
Division always emits a div instruction |
gcc -O2 lowers division by 10 to a multiply and a shift |
| Bit-twiddling operations need a loop | popcnt, tzcnt, blsr, and andn each execute in a single instruction |
Branches, Prediction, and cmov
A modern CPU core doesn’t wait for cmp to finish before picking the next instruction address. The hardware branch predictor chooses a direction, and the core speculatively executes down that path—flushing and rolling back its work if the guess turns out wrong. As a result, a branch’s cost depends not on the jcc instruction itself, but on how predictable its outcome is.
To measure this fairly, we need an array where comparing each element against the running maximum produces an unpredictable outcome. The testbed generator enforces that explicitly: with probability 1/2, the next element sets a new peak; otherwise, it stays below it. A second array holds the exact same numbers sorted in ascending order.
for (i = 0; i < N_ELEMS; i++) {
int32_t value = 0;
if ((next_rand(&state) & 1u) != 0u) {
peak += 1 + (int32_t)(next_rand(&state) % 1000u);
value = peak;
} else {
value = peak - 1 - (int32_t)(next_rand(&state) % 1000u);
}
adv_arr[i] = value;
sorted_arr[i] = value;
}
qsort(sorted_arr, N_ELEMS, sizeof(*sorted_arr), compare_i32);Both kernel implementations take the exact same array and share the same prototype. Only the maximum-update mechanism differs.
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; maxel.asm — maximum of an int32_t array: branchy vs. branchless cmov.
default rel
section .text
global asm_max_branchy
global asm_max_cmov
; ------------------------------------------------------------------------------
; int32_t asm_max_branchy(const int32_t *arr, size_t len)
; Input: rdi = arr, rsi = len (len >= 1)
; Output: eax = maximum element
; Clobbers: rax, rcx, rdx, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_max_branchy:
mov eax, dword [rdi]
mov rcx, 1
cmp rcx, rsi
jae .done
.loop:
mov edx, dword [rdi + rcx * 4]
cmp edx, eax
jle .skip
mov eax, edx
.skip:
inc rcx
cmp rcx, rsi
jb .loop
.done:
ret
; ------------------------------------------------------------------------------
; int32_t asm_max_cmov(const int32_t *arr, size_t len)
; Input: rdi = arr, rsi = len (len >= 1)
; Output: eax = maximum element
; Clobbers: rax, rcx, rdx, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_max_cmov:
mov eax, dword [rdi]
mov rcx, 1
cmp rcx, rsi
jae .done
.loop:
mov edx, dword [rdi + rcx * 4]
cmp edx, eax
cmovg eax, edx
inc rcx
cmp rcx, rsi
jb .loop
.done:
ret
section .note.GNU-stack noalloc noexec nowrite progbitsThe cmov instruction differs from jcc + mov in that it never alters rip.
Inside the loop, each instruction plays a clear role:
mov edx, dword [rdi + rcx * 4]loads the nextint32_tvia SIB addressing;cmp edx, eaxcompares the candidate against the current maximum;jle .skipin the branchy version jumps over the update;cmovg eax, edxin the branchless version performs the update without branching.
Benchmark across 1,048,576 elements (best of seven runs):
n = 1048576
adversarial branchy: 5.35 ns/elem
adversarial cmov: 0.84 ns/elem
sorted branchy: 0.44 ns/elem
sorted cmov: 0.84 ns/elem
max: okReading those numbers:
- On unpredictable data, the branch costs
5.35ns per element whilecmovtakes0.84ns, because roughly half the branches flush the pipeline. - On sorted data, the branch is nearly 100% predictable and drops to
0.44ns, whilecmovremains pinned at0.84ns. cmovdoesn’t speed up the loop by magic: it eliminates branch mispredictions, but creates a loop-carried data dependency chain througheaxacross every iteration.
| Variant | Mispredictions | What happens | Time |
|---|---|---|---|
branchy, sorted |
~0 | pipeline never flushes | 0.44 ns/elem |
branchy, adversarial |
~50% | pipeline flush costing 15–20 cycles | 5.35 ns/elem |
cmov, either |
0 | eax waits on the previous eax |
0.84 ns/elem |
perf stat: Where the Cycles Actually Go
Hardware performance counters confirm it isn’t about code size. Both commands run the exact same harness with the exact same array generator; only the selected kernel changes.
$ perf stat -e cycles:u,instructions:u,branches:u,branch-misses:u \
./build/bench adversarial branchy
adversarial branchy: 4.66 ns/elem
285,700,898 cycles:u
444,834,837 instructions:u
93,088,218 branches:u
5,684,583 branch-misses:u
$ perf stat -e cycles:u,instructions:u,branches:u,branch-misses:u \
./build/bench adversarial cmov
adversarial cmov: 0.65 ns/elem
204,344,486 cycles:u
441,162,397 instructions:u
85,748,173 branches:u
2,023,394 branch-misses:uperf statmeasures the entire./build/benchprocess—including the random array generator loop (if ((next_rand(...) & 1u) != 0u)) and theqsortcall before the timed kernel—which is why even the branchlesscmovrun still records ~85.7M branches and ~2M branch misses from the surrounding harness.instructionsdiffer by just 0.8% (444.8Mvs.441.2M), proving the branchy version isn’t executing meaningfully more instructions.- The delta in
branch-missesis3.66M—roughly half of the7 × 1,048,575 ≈ 7.34Munpredictable comparisons (7 iterations over2^20elements) insideasm_max_branchy. cyclesdiffer by81.4M, meaning each extra misprediction cost roughly twenty pipeline cycles.
Access to performance counters is gated by /proc/sys/kernel/perf_event_paranoid. On this machine it is set to 2, so only userspace events with the :u suffix are accessible without root, while kernel counters are locked out. You can check the setting with:
$ cat /proc/sys/kernel/perf_event_paranoid
2For comparing user-space code, :u counters are all you need.
Division by a Constant
The technique of division by a constant has been a staple of compilers for decades, yet in a disassembly listing it looks like an ordinary multiply and is easy to overlook.
For uint32_t and a divisor of 10, the multiplier is:
- the magic multiplier replacing division by 10.
In C99, the same trick fits on one line. The compiler lowers it to a multiply by 0xCCCCCCCD and a right shift by 35: our NASM testbed uses mul and shr, while GCC and Clang emit imul rax, reg plus shr rax, 35.
uint32_t div10(uint32_t x) { return (uint32_t)(((uint64_t)x * 0xCCCCCCCDULL) >> 35); }; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
; div10.asm — uint32_t division by 10 via magic-constant multiplication.
default rel
section .text
global asm_div10
global asm_div10_hw
; ------------------------------------------------------------------------------
; uint32_t asm_div10(uint32_t x)
; Input: edi = x
; Output: eax = x / 10
; Clobbers: rax, rdx, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_div10:
mov eax, edi
mov edx, 0xCCCCCCCD
mul edx
shr edx, 3
mov eax, edx
ret
; ------------------------------------------------------------------------------
; uint32_t asm_div10_hw(uint32_t x)
; Input: edi = x
; Output: eax = x / 10
; Clobbers: rax, rcx, rdx, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_div10_hw:
mov eax, edi
xor edx, edx
mov ecx, 10
div ecx
ret
section .note.GNU-stack noalloc noexec nowrite progbitsIn objdump, the magic-constant version disassembles to:
0000000000000000 <asm_div10>:
0: 89 f8 mov eax,edi
2: ba cd cc cc cc mov edx,0xcccccccd
7: f7 e2 mul edx
9: c1 ea 03 shr edx,0x3
c: 89 d0 mov eax,edx
e: c3 retmov edx, 0xcccccccdloads the multiplier from the formula;mul edxmultiplieseaxbyedxand writes the 64-bit product acrossedx:eax;shr edx, 3takes the upper 32 bits and divides them by 8, since ;mov eax, edxmoves the quotient into the return register.
eax × 0xCCCCCCCD = [ edx : eax ] (64-bit product from mul edx)
│
├─ eax: bits 31..0
└─ edx: bits 63..32
shr edx, 3 ──► bits 63..35 (effective shift >> 35)The testbed checks both implementations across 100 million consecutive inputs and one million pseudorandom inputs, then benchmarks per-call latency:
div10(123456789) = 12345678
magic: 1.38 ns/call
div: 2.42 ns/call
div10: okNote that 1.38 and 2.42 ns include function call overhead and storing the result into a volatile sink, so this measures the loop body rather than raw instruction latency. Even with that overhead, hardware div is nearly twice as expensive as multiplication on this core.
BMI: One Instruction Instead of a Loop
The same principle applies to bit manipulation. The kernels in bmi_demo.asm collapse each bit operation down to a single instruction:
asm_popcount64:
popcnt rax, rdi
ret
asm_tzcnt64:
tzcnt rax, rdi
ret
asm_blsr:
blsr rax, rdi
ret
asm_andn:
andn rax, rsi, rdi
retIn the disassembly, popcnt encodes as f3 48 0f b8 c7: here f3 is part of the instruction’s mandatory opcode prefix, not a string-repeat prefix. asm_blsr computes x & (x - 1), clearing the lowest set bit; asm_andn returns a & ~b, and the operand order andn rax, rsi, rdi reflects the instruction’s semantics of inverting its first source operand ((~src1) & src2). The bmi_test.c harness verifies edge cases including tzcnt(0) = 64:
popcnt(0xF0F0F0F0F0F0F0F0) = 32
tzcnt(0x8000) = 15
bmi: okpopcnt, tzcnt, blsr, and andn belong to the ABM/BMI1 extensions. This CPU supports them, but portable binaries must query CPUID first or risk SIGILL on older hardware; the full ISA feature matrix is covered in lesson 25.
Terminal Verification
All numbers above can be reproduced with three commands from the lesson directory:
$ make test
20-optimization: branch/cmov, div10 and BMI tests OK
$ perf stat -e cycles:u,branch-misses:u ./build/bench adversarial branchy
$ perf stat -e cycles:u,branch-misses:u ./build/bench adversarial cmovThe testbed prints max: ok only if both maximum implementations return identical results on both arrays. The div10 and bmi suites verify full ranges and boundary cases rather than a single sample input.
SIMD vector instructions (covered in lesson 21) follow the same philosophy: instead of shaving cycles off a single element, they eliminate entire loop iterations.
Common Failure Modes
-
Assuming
cmovis always faster than a branch.
Symptom: On a sorted array, the branchy version runs at0.44 ns/elemwhilecmovtakes0.84 ns/elem.
Cause:cmovg eax, edxdepends on the previous iteration’seax, serializing the loop into a strict dependency chain.
Fix: Choose between branching andcmovbased on data predictability, not instruction count. -
Treating a branch misprediction as just one wasted instruction.
Symptom:perf statshows5,684,583misses vs.2,023,394, creating an81.4Mcycle gap.
Cause: On a misprediction, the core discards all speculatively executed instructions and refills the pipeline from scratch.
Fix: Measurebranch-misses:ubefore and after changing code, and restructure the data or algorithm rather than guessing from disassembly length. -
Expecting every hot-loop division to show up as
div.
Symptom:gcc -O2compiles division by 10 intomulandshr, leavingdivonly in the hand-writtenasm_div10_hw.
Cause: When the divisor is a compile-time constant, the compiler replacesdivwith magic-number multiplication.
Fix: Look formulwith an unusual hex constant paired with a right shift, not just thedivmnemonic. -
Thinking
popcntandtzcntare libc helpers.
Symptom:objdumpshowspopcnt rax,rdiandtzcnt rax,rdiinline with no calls or loops.
Cause: These are native ABM/BMI1 instructions, notlibcroutines.
Fix: Guard them behindCPUIDchecks if targeting older CPUs, and avoid writing manual bit-counting loops where hardware instructions exist. -
Trusting a single benchmark run.
Symptom: Two runs of the exact same branchy kernel yielded5.35and4.66 ns/elem.
Cause: CPU boost clocks, cache warm-up, and background noise skew individual measurements.
Fix: Take the best of multiple runs, corroborate timings withperfhardware counters, and record the CPU model alongside any benchmark numbers.
Lab
Goal. Implement asm_max3(int32_t a, int32_t b, int32_t c) to return the maximum of three signed integers without conditional jumps, and verify with perf that it executes branch-free.
Contract.
- Inputs: three signed 32-bit integers in the System V ABI registers.
- Output:
eax. - Must not write to memory or clobber
callee-savedregisters. - The C99 test harness checks all combinations from
{INT32_MIN, -1, 0, 1, INT32_MAX}plus one million random triples.
Acceptance criteria.
make testpasses.objdump -d -M intelcontains nojccinstructions insideasm_max3.perf stat -e branches:u,branch-misses:u ./build/max3_testconfirms branch misses do not scale with the number of calls over a million triples.
Hints, expected output, and walkthrough
For two numbers, a branchless maximum takes two instructions: cmp and cmovl (or cmovg). For three numbers, simply repeat that pair—keeping in mind that cmov reads the flags set by the most recent cmp.
Expected testbed output:
max3: 1000000 cases ok
max3: no conditional jumps in kernelIf jle or jg shows up in the disassembly, either the compiler or your manual implementation left a branch behind: verify that updates happen through cmov rather than jumping around a mov.
Testbed sources, Makefile, and automated tests for this lesson: lessons/20-optimization.
Summary
- A branch’s cost is governed by direction predictability, not the
jccinstruction itself. cmoveliminates branch mispredictions at the price of a data dependency on the previous value.- On predictable data, a conditional branch can be twice as fast as a branchless
cmov. - Compilers replace division by a constant with multiplication by a magic constant and a right shift.
popcnt,tzcnt,blsr, andandnexecute bit-manipulation operations in a single instruction.- Performance claims must be backed by
perfhardware counters rather than a single wall-clock timing.
int32_t values at once: AVX2, ymm registers, CPUID/XCR0 feature checks, and why vzeroupper is mandatory on exit.