在内核代码中经常见到likely和unlikely宏。
The macros are defined as :
#define likely(x) __builtin_expect((x),1)The __builtin_expect is a method that gcc (versions >= 2.96) offer for programmers to indicate branch prediction information to the compiler. The return value of __builtin_expect is the first argument (which could only be an integer) passed to it.
#define unlikely(x) __builtin_expect((x),0)
To check it out how it could be beneficial, an excerpt from "info gcc" :
if (__builtin_expect (x, 0))Based on this information the compiler generates intelligent code, such that the most expected result is favored.
foo ();
[This] would indicate that we do not expect to call `foo', since we
expect `x' to be zero.
__builtin_expect (exp, val)只是在我们实现代码时能够预见exp的值很有可能会是val,
编译时通过这个宏把我们的预期告诉编译器,编译器按照这个预期会生成更高效的可执行代码。
该宏的返回值为exp,exp只能是整型。