Question

GCC compiler supports __builtin_expect statement that is used to define likely and unlikely macros.

eg.

#define likely(expr)    (__builtin_expect(!!(expr), 1))
#define unlikely(expr)  (__builtin_expect(!!(expr), 0))

Is there an equivalent statement for the Microsoft Visual C compiler, or something equivalent ?

Was it helpful?

Solution

I say just punt

There is nothing like it. There is __assume(), but don't use it, it's a different kind of optimizer directive.

Really, the reason the gnu builtin is wrapped in a macro is so you can just get rid of it automatically if __GNUC__ is not defined. There isn't anything the least bit necessary about those macros and I bet you will not notice the run time difference.

Summary

Just get rid of (null out) *likely on non-GNU. You won't miss it.

OTHER TIPS

According to http://www.akkadia.org/drepper/cpumemory.pdf (page 57), it still makes sense to use static branch prediction even if CPU predicts correctly dynamically. The reason for that is that L1i cache will be used even more efficiently if static prediction was done right.

C++20 standard will include [[likely]] and [[unlikely]] branch prediction attributes.

The latest revision of attribute proposal can be found from http://wg21.link/p0479

The original attribute proposal can be found from http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0479r0.html

Programmers should prefer PGO. Attributes can easily reduce performance if applied incorrectly or they later become incorrect when program changes.

__assume should be similar.

However, if you want to do this really well you should use Profile Guided Optimization rather than static hints.

According to Branch and Loop Reorganization to Prevent Mispredicts document from Intel:

In order to effectively write your code to take advantage of these rules, when writing if-else or switch statements, check the most common cases first and work progressively down to the least common.

Unfortunately you cannot write something like

#define if_unlikely(cond) if (!(cond)); else 

because MSVC optimizer as of VS10 ignores such "hint".

As I prefer to deal with errors first in my code, I seem to write less efficient code. Fortunately, second time CPU encounters the branch it will use its statistics instead of a static hint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top