likely() ,unlikely() 与指令预取

在代码中常常会看见likely()和unlikely()的用法,尤其是linux内核代码中.

if(likely(value)) 等价于 if(value)

if(unlikely(value)) 也等价于 if(value)

从代码理解上,它们的效果是一致的,那么他们的区别在哪里呢?

 

这2个宏在compiler.h中如下定义:

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

 

GCC的文档中如是说:

— Built-in Function: long __builtin_expect (long exp, long c)

You may use __builtin_expect to provide the compiler with branch prediction information. In general, you should prefer to use actual profile feedback for this (-fprofile-arcs), as programmers are notoriously bad at predicting how their programs actually perform. However, there are applications in which this data is hard to collect.

The return value is the value of exp, which should be an integral expression. The semantics of the built-in are that it is expected that exp == c. For example:

          if (__builtin_expect (x, 0))
            foo ();

indicates that we do not expect to call foo, since we expect x to be zero. Since you are limited to integral expressions for exp, you should use constructions such as

          if (__builtin_expect (ptr != NULL, 1))
            foo (*ptr);

when testing pointer or floating-point values.

好吧,一句话总结,就通过编译优化,使得代码指令的预取能够更高效.

具体的测试代码,可以参考后面的url:

 

参考url:

http://blog.csdn.net/rstevens/article/details/1798561

http://kernelnewbies.org/FAQ/LikelyUnlikely

http://caisenchen.blog.163.com/blog/static/55286550200871131855311/

http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

原文地址:https://www.cnblogs.com/xuxm2007/p/3136145.html