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 ishard 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.
unlikely的定义如下:
#define unlikely(x) __builtin_expect(!!(x), 0)
也就是说我们期望表达式x的值为0,从而如果我们用
…….
if(unlikely(x)){
bar();
}
来测试条件的话,我们就不期望bar()函数执行,所以该宏的名字用unlikely也就是不太可能来表示。
likely宏与次类似.
说到底__builtin_expect函数就是为了优化可能性大的分支程序。
if() 语句你照用, 跟以前一样, 只是 如果你觉得if()是1 的可能性非常大的时候, 就在表达式的外面加一个likely() , 如果可能性非常小(比如几率非常小),就用unlikely() 包裹上。
阅读(1194) | 评论(0) | 转发(0) |