How Linux's 'unlikely' macro helps compilers optimize branch prediction
The Linux kernel source code uses a macro called 'unlikely' to give the compiler advance information about which code branches are rarely executed. This macro wraps GCC's built-in '__builtin_expect' function, signaling that a given condition is expected to evaluate to zero, or false, most of the time. Armed with this hint, the compiler reorders assembly output so the common code path executes without an extra jump, improving CPU branch prediction efficiency. A comparison of compiled assembly for two near-identical loops — one using 'likely' and one using 'unlikely' — shows the branches arranged in opposite order, confirming the macro's effect. When used correctly, the technique can meaningfully boost performance; when misapplied, it can hurt it.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in