liveBook · Manning

Branch prediction

As explained in Hacking Cryptography

Branch prediction is a processor mechanism that forecasts the outcome or target of a control-flow branch to keep instruction execution supplied.

Branch prediction forecasts which control-flow path a conditional branch will take, helping the processor keep execution supplied. Predictable patterns run faster than irregular ones, so secret-dependent branches can make runtime vary with data. section 10.5

Summing values above a threshold

A C loop summing values above 500 runs two to three times faster on a sorted 100-million-element array than on an unsorted array of the same size. Sorting produces long runs of not-taken and taken branches, while unsorted data produces an irregular pattern. section 10.5

Avoid data-dependent control-flow variation when constant-time behavior matters:

  • Replace the conditional branch with a conditional move where appropriate; CMOV updates a value according to a comparison without diverging into separate code paths. section 10.5

How Hacking Cryptography covers it

How deep it goes
Demonstrates prediction patterns, compares timings, and reaches CMOV-based code, but does not detail predictor hardware internals.
Examples
Uses a threshold-summing loop, sorted and unsorted arrays, CMOV inline assembly, and measured GCC program output.
What it assumes
Assumes familiarity with C loops and comparisons while introducing branch prediction, taken and missed paths, and CMOV behavior.
What you can do after
Diagnose performance variation by comparing branch patterns and apply conditional moves to construct a branchless implementation.
How it connects
Connects branch prediction with control flow, constant-time programming, conditional moves, and processor execution.

Also explained in

Compare how 2 books explain branch prediction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Hacking Cryptography. The section links point to the parts of the book it draws on.