Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable branch prediction hint in c++

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?

like image 700
Emile D. Avatar asked Jan 05 '18 21:01

Emile D.


1 Answers

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

like image 68
Davis Herring Avatar answered Nov 12 '22 13:11

Davis Herring