On this page

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.

c
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.

maxel.asm
; 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 progbits

The 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 next int32_t via SIB addressing;
  • cmp edx, eax compares the candidate against the current maximum;
  • jle .skip in the branchy version jumps over the update;
  • cmovg eax, edx in 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: ok

Reading those numbers:

  • On unpredictable data, the branch costs 5.35 ns per element while cmov takes 0.84 ns, because roughly half the branches flush the pipeline.
  • On sorted data, the branch is nearly 100% predictable and drops to 0.44 ns, while cmov remains pinned at 0.84 ns.
  • cmov doesn’t speed up the loop by magic: it eliminates branch mispredictions, but creates a loop-carried data dependency chain through eax across 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:u
  • perf stat measures the entire ./build/bench process—including the random array generator loop (if ((next_rand(...) & 1u) != 0u)) and the qsort call before the timed kernel—which is why even the branchless cmov run still records ~85.7M branches and ~2M branch misses from the surrounding harness.
  • instructions differ by just 0.8% (444.8M vs. 441.2M), proving the branchy version isn’t executing meaningfully more instructions.
  • The delta in branch-misses is 3.66M—roughly half of the 7 × 1,048,575 ≈ 7.34M unpredictable comparisons (7 iterations over 2^20 elements) inside asm_max_branchy.
  • cycles differ by 81.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
2

For 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:

m=⌈23510⌉=3435973837=0xCCCCCCCD m = \left\lceil \frac{2^{35}}{10} \right\rceil = 3435973837 = \mathtt{0xCCCCCCCD}
where
mm
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); }
div10.asm
; 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 progbits

In 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                   	ret
  • mov edx, 0xcccccccd loads the multiplier from the formula;
  • mul edx multiplies eax by edx and writes the 64-bit product across edx:eax;
  • shr edx, 3 takes the upper 32 bits and divides them by 8, since 235=232⋅82^{35} = 2^{32} \cdot 8;
  • mov eax, edx moves 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: ok

Note 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

    ret

In 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: ok

popcnt, 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 cmov

The 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

  1. Assuming cmov is always faster than a branch.
    Symptom: On a sorted array, the branchy version runs at 0.44 ns/elem while cmov takes 0.84 ns/elem.
    Cause: cmovg eax, edx depends on the previous iteration’s eax, serializing the loop into a strict dependency chain.
    Fix: Choose between branching and cmov based on data predictability, not instruction count.

  2. Treating a branch misprediction as just one wasted instruction.
    Symptom: perf stat shows 5,684,583 misses vs. 2,023,394, creating an 81.4M cycle gap.
    Cause: On a misprediction, the core discards all speculatively executed instructions and refills the pipeline from scratch.
    Fix: Measure branch-misses:u before and after changing code, and restructure the data or algorithm rather than guessing from disassembly length.

  3. Expecting every hot-loop division to show up as div.
    Symptom: gcc -O2 compiles division by 10 into mul and shr, leaving div only in the hand-written asm_div10_hw.
    Cause: When the divisor is a compile-time constant, the compiler replaces div with magic-number multiplication.
    Fix: Look for mul with an unusual hex constant paired with a right shift, not just the div mnemonic.

  4. Thinking popcnt and tzcnt are libc helpers.
    Symptom: objdump shows popcnt rax,rdi and tzcnt rax,rdi inline with no calls or loops.
    Cause: These are native ABM/BMI1 instructions, not libc routines.
    Fix: Guard them behind CPUID checks if targeting older CPUs, and avoid writing manual bit-counting loops where hardware instructions exist.

  5. Trusting a single benchmark run.
    Symptom: Two runs of the exact same branchy kernel yielded 5.35 and 4.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 with perf hardware 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-saved registers.
  • The C99 test harness checks all combinations from {INT32_MIN, -1, 0, 1, INT32_MAX} plus one million random triples.

Acceptance criteria.

  1. make test passes.
  2. objdump -d -M intel contains no jcc instructions inside asm_max3.
  3. perf stat -e branches:u,branch-misses:u ./build/max3_test confirms 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 kernel

If 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

  1. A branch’s cost is governed by direction predictability, not the jcc instruction itself.
  2. cmov eliminates branch mispredictions at the price of a data dependency on the previous value.
  3. On predictable data, a conditional branch can be twice as fast as a branchless cmov.
  4. Compilers replace division by a constant with multiplication by a magic constant and a right shift.
  5. popcnt, tzcnt, blsr, and andn execute bit-manipulation operations in a single instruction.
  6. Performance claims must be backed by perf hardware counters rather than a single wall-clock timing.
Bridge to the next lesson
A scalar loop hits a ceiling at one dependency per iteration. In lesson 21, we move to instructions that process eight int32_t values at once: AVX2, ymm registers, CPUID/XCR0 feature checks, and why vzeroupper is mandatory on exit.