Order of expressions to minimize branch mis-predictions?

Jeffrey Walton noloader@gmail.com
Wed Sep 28 15:09:00 GMT 2016


Hi Everyone,

Intel has a document called "Branch and Loop Reorganization to Prevent
Mispredicts" (https://software.intel.com/en-us/articles/branch-and-loop-reorganization-to-prevent-mispredicts).
In the document, they say to:

    if ( C )     // most common case
        ...
    else if ( A )     // 2nd most common case
        ...
    else if ( B )     // 3rd most common case
        ...

They also say to:

    switch ( v )
    {
        default:    // most common case
            ...
        case S:     // 2nd most common case
            ...
        case R:     // 2nd most common case
            ...
        case T:     // 2nd most common case
            ...
    }

Above, (A,B,C) and (R,S,T) are ordered based on profiling data, so we
know 'C' is most common in the first example, and 'default' is most
common in the second example.

My question is, does the same hold for GCC? Should the most likely
statement appear first to provide a hint to the compiler?

Related, we tried to provide the hints via __builtin_expect, but
benchmarking showed the program mostly slowed down by a small amount
rather than speed up.

My apologies if this horse has been beat to death. I'm trying to find
a canonical answer, but search is failing me. Cf.,
https://www.google.com/search?q=gcc+"branch+prediction"+order+of+statements+site%3Agcc.gnu.org

Thanks in advance.



More information about the Gcc-help mailing list