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?
if
-else
call has no effect on the resulting assembly, even though any observer could easily tell that in one version, theif
block is less likely, and in the other, theelse
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