开发者

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

开发者 https://www.devze.com 2023-02-12 18:53 出处:网络
We have a macro for error-checking that goes like this: #define CheckCondition( x ) \\ if( x ) { \\ //okay, do nothing开发者_StackOverflow \\

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

#define CheckCondition( x ) \
    if( x ) { \
    //okay, do nothing开发者_StackOverflow \
    } 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消