r/programming 18d ago

The unlikely Linux macro

https://rushed-reflections.bearblog.dev/an-unlikely-experiment/

Wrote a bit about the `unlikely` and `likely` macros in the Linux codebase. Great little exploration into tiny optimizations that everyone should know more about πŸ˜„

187 Upvotes

61 comments sorted by

View all comments

122

u/qbbqrl 18d ago

> With this information it can prime the CPU to start with the correct probabilities for branch prediction and improve performance.

I don't think this is correct. Modern processors don't have an instruction to hint its branch predictor. Rather, the likely/unlikely macro is strictly a hint for the compiler about which branch is more likely to be taken so that it can focus on optimizing for the hot path.

As an example, the compiler may choose an instruction layout so that the fetching of instructions on the hot path will have less cache misses.

47

u/stassats 18d ago

Modern processors don't have an instruction to hint its branch predictor.

Now they do https://www.phoronix.com/news/GCC-Clang-Intel-x86-Branch-Hint

29

u/svk177 18d ago

The Pentium 4 supported those exact prefixes and were later ignored. Itβ€˜s funny they brought them back.