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?
C++20 is, er, likely to have attributes for the purpose. (The Committee Draft is still being reviewed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With