likely/unlikely equivalent for MSVC

江枫思渺然 提交于 2019-11-27 18:42:09
DigitalRoss

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.

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.

Pauli Nieminen

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.

Michael

__assume should be similar.

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

Vyacheslav Lanovets

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!