likely/unlikely equivalent for MSVC

前端 未结 6 1571
醉话见心
醉话见心 2020-12-02 18:19

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

eg.

#define likely(expr)    (__builtin_expect(!!(         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 18:55

    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.

提交回复
热议问题