Linux内核源码中两个宏定义likely,unlikely

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

由于刚开始学习linux内核源码,所以对源码中经常见到的两个宏定义不是很理解,现在对其进行详细剖析。

定义中出现了一个GCC的内建函数:_builtin_expect(),其定义如下:

long __builtin_expect (long exp, long c)                                    [Built-in Function]
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 value of c must be a compile-time constant. The semantics of the built-in are that it is expected that exp == c. For example:
if (__builtin_expect (x, 0))
foo ();
would indicate 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))
error ();
when testing pointer or floating-point values.

上诉定义大致就是说,很多程序员对程序实际运行的预测都很糟糕,所以GCC提供了内建函数供处理分支预测,优化程序。

这个函数的返回值是一个整型表达式:exp,而且这个表达式很大程度上会等于另一个常量 c,即:exp == c

这样对unlikely和likely函数就很好理解了:

likely(x) :就是x的值一般情况下会等于1;

unlikely(x):就是x的值一般情况下会等于0。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值