likely(x)和unlikely(x)

#define likely(x) __builtin_expect((x),1)

#define unlikely(x) __builtin_expect((x),0)

__builtin_expect() GCC (version >= 2.96)提供给程序员使用的,目的是将分支转移的信息提供给编译器,这样编译器可以对代码进行优化,以减少指令跳转带来的性能下降。

__builtin_expect((x),1) 表示 x 的值为真的可能性更大;__builtin_expect((x),0) 表示 x 的值为假的可能性更大。

附:

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.

原文:

[1]http://wenku.baidu.com/view/dae3a5eb172ded630b1cb621.html

[2]http://linux.chinaunix.net/techdoc/develop/2007/08/31/966838.shtml

[3]http://hi.baidu.com/lxk3480/item/91eae1c6c1690124a0b50ae5

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

原文地址:https://www.cnblogs.com/mydomain/p/2924034.html