News for hackers. Stuff that matters.
Re:Branch predictor: How many “if”s are too many? by berkut on Thursday May 06, 2021 @04:30PM (#27068708)
You can use the __builtin_expect keyword on GCC and clang.

It does make a difference (HPC code uses it quite a bit because of this), but as it's done manually, results obviously vary depending on processor, and there's a limit to how far you can take it. Trying not to branch (not always possible) is best...

Basically, it's like manually doing profile-guided optimisation - you look at perf or vtune, and add the above to branches which have a high penalty and which are rarely or often taken, and see if it makes a difference.

Re:Branch predictor: How many “if”s are too many? by Veedrac on Thursday May 06, 2021 @04:46PM (#27068855)
Note that this is not targeted to branch prediction, but compiler optimizations. It should be done carefully, because it tends to have a larger downside than its upside, and the changes the compiler makes based on it can be unpredictable, and unstable.

> Trying not to branch (not always possible) is best...

Branches are often faster than branch-free methods, since they can speculate certain data dependencies away.

Re:Branch predictor: How many “if”s are too many? by berkut on Thursday May 06, 2021 @05:53PM (#27069482)
> Branches are often faster than branch-free methods, since they can speculate certain data dependencies away.

And often they're slower, since predicting some branches is often impossible due to the data :) So the processor ends up miss-predicting most of the time, thinking it knows what happened last time.

It all depends on what you're doing.