Master the fundamental concepts of compiler optimization techniques through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it works__builtin_expect(expr, c) tells GCC/Clang the probability of a branch, influencing layout so the hot path falls through. Linux kernel likely()/unlikely() macros wrap it. Mis-hinting can slow code by fighting the hardware predictor.
Mark error checks as cold. Keep the common path straight-line when possible.
cLoading…
perf stat -e branch-misses before sprinkling hintsKeep the relevant documentation open while you implement. When your output disagrees with the reference, trace one failing case by hand before changing random lines.
You will add branch hints to a hot path and compare assembly layout. This exercise requires explaining when hints helped versus when the predictor already learned the branch.
Document one invariant you will assert in tests and how you would detect its violation from observable symptoms.
likely()/unlikely() (__builtin_expect) do not talk to the CPU's branch predictor. They tell the compiler which side of an if to lay out as the fall-through path. The unlikely side moves out of line, so the common case runs straight through without a taken jump. Model this. For each branch, lay the code out with and without the hint, run the recorded condition outcomes through a 2-bit predictor, and charge for taken jumps and mispredictions. Wrong hints should visibly hurt.
cLoading…
OUTCOMES is a list of tokens made of T (condition true) and N (false), each optionally repeated with *COUNT. For example N*999 T, or TN*50 for 100 alternating outcomes. At most 100000 outcomes per branch.
likely), the then block falls through, and the conditional jump is taken when the condition is false. With unlikely, the then block is moved out of line: the else/continuation falls through, and the jump is taken when the condition is true. The "without hint" run always uses the default layout.likely while the condition is true less than half the time, or unlikely while it is true more than half the time.cLoading…
The percentage is rounded half up to 1 decimal. Errors: branch NAME: hint must be likely, unlikely or none, branch NAME: bad outcome list, and penalty: must be >= 0.
Input:
cLoading…
Output:
cLoading…
Hidden tests cover a likely hint that is wrong, a pattern that defeats the 2-bit counter, custom penalties including a zero taken-jump cost (so only mispredictions matter), a single-outcome branch, and malformed outcome lists.