Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hint to Visual C++ compiler optimizer that a specific branch of an if-statement is unlikely to be executed?

We have a macro for error-checking that goes like this:

#define CheckCondition( x ) \
    if( x ) { \
    //okay, do nothing \
    } else { \
       CallFunctionThatThrowsException(); \
    }

and normally the condition has to be true and we'd like the CPU branch prediction to always select this path, and if it happens to be false we don't really care of a misprediction - throwing an exception and massive stack unwinding will cost a fortune anyway.

According to CPU hardcore descriptions branch prediction will treat forward jumps and backward jumps slightly differently (something like a backward jump is always performed and a forward jump is never performed) and the compiler could improve branch prediction by generating code that will give right hints to the CPU branch predictor.

gcc seems to have likely and unlikely hints for that. Is there anything like that in Visual C++? Can __assume keyword be used for that?

like image 386
sharptooth Avatar asked Feb 22 '11 07:02

sharptooth


2 Answers

Not in MSVC, unfortunately, according to their developer center.

It's very frustrating because we'd like to use it in a couple of cases where the equivalent GCC intrinsic has saved us a critical few microseconds in inner loops, but the closest we can get is to swap the if and else clauses so that the more likely case is in the forward-jump-not-taken branch.

like image 99
Crashworks Avatar answered Nov 13 '22 10:11

Crashworks


Enable Profile-Guided Optimization. The compiler not only will maximize branch prediction, but may move the cold code out of the way entirely. This channel 9 video explains the various optimizations.

like image 30
Bruno Martinez Avatar answered Nov 13 '22 11:11

Bruno Martinez