#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。