12 ms·
you can also use likely and unlikely to help the branch prediction.
by synergy20 3y ago
you can also use likely and unlikely to help the branch prediction.
- menaerus 3y agoIt's a common myth that I hear a lot - it has nothing to do with the branch-prediction per se. It's only a hint to the compiler itself to emit a more instruction-cache and CPU-decode friendly code layout. E.g. codegen for unlikely branch(es) in the binary itself will be placed farther away from the "likely" execution path.
- NobodyNada 3y agoThere's a grain of truth to it -- when a CPU encounters a branch it has not seen before, some CPUs (but not most modern ones: https://stackoverflow.com/a/51848422 https://stackoverflow.com/a/51848422) have static prediction that assumes a backwards branch is taken and a forwards branch is not. And compilers tend to put "unlikely" execution paths past the bottom of the function so that they're not interrupting the "hot path" of the function. So if the processor uses static branch prediction, or if it hasn't executed the function before and doesn't know there's a branch there until after it's been fetched, the branch predictor is more likely to follow the "hot path" than a forwards jump that skips ahead. But yeah, static branch prediction isn't common anymore, and "likely"/"unlikely" intrinsics have more to do with tuning the optimizer than the branch predictor.