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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With