Portable branch prediction hint in c++
Asked Answered
O

1

5

Branches prediction have been addressed a couple of time on StackOverflow. However, I didn't specifically found the answer to what I am looking for.
During the optimization phase, I need to avoid branch misprediction. And I have a number of verification that I need to do. It looks like:

if(!successCondition)
    { throw Something(); }

Of course, in the normal expected workflow, which happen most of the cases, we don't throw exception, thus we don't enter the if.

I know that in the common if/else paradigm, we can hint the compiler by putting the most likely branch in the if, and the less likely in the else (Portable branch prediction hints). But I do not want (because of the readability) chain the ifs:

if(successCondition)
    { whatever(); }
else
    { throw Something(); }

Thus, I understand that the compiler will, by default, favor the entry in the if and I will get a branch misprediction.

I know that gcc has a specific function to optimize the code, which is called with unlikely in the Linux kernel (Branch-aware programming). But it is not portable, and I need my code to be.

Is there a way to have the correct branch prediction in C++ that remains portable?

Orren answered 5/1, 2018 at 21:42 Comment(3)
On most modern compilers, the two versions of the code you wrote will result in equivalently performant code. The Assertion made by the answer you linked (that reversing the conditions around will somehow result in more performant code) sounds like the advice of someone who didn't actually profile their code or examine the resulting assembly of their program....Chavis
Case in point: Note in this example (godbolt.org) that reversing the conditions of the if-else call has no effect on the resulting assembly, even though any observer could easily tell that in one version, the if block is less likely, and in the other, the else block is less likely. Compilers optimize aggressively around these kinds of constructs, and trying to out-smart them won't make your code faster—just harder to read.Chavis
@Chavis -That is indeed an interesting code snippet, that shows that the compiler is very powerful (GCC is way more powerful than I thought). However, I guess that the Linux developer spicing their code with "likely" or "unlikely" keyword have a motivation to do so. I do agree that we should avoid premature optimization, that the compiler is generally very good, that hardware designer tends to work hard to avoid branch misprediction (using a perceptron these days if I am right); I still think that it can be useful in some cases.Orren
L
7

C++20 is, er, likely to have attributes for the purpose. (The Committee Draft is still being reviewed.)

Luff answered 5/1, 2018 at 22:13 Comment(1)
It is here now! en.cppreference.com/w/cpp/language/attributes/likely :)Anthracene

© 2022 - 2024 — McMap. All rights reserved.