#define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0)
它的功用比較像是提醒compiler這個判斷式比較容易為真或比較容易為假
進而調整pipeline...
比較可能執行的放到較近的地方,比較不可能執行的放到較遠的地方
以下是 __builtin_expect的說明
__builtin_expect(),查閲GCC手册,發現其定義如下:
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.
大概是說我們可以用__builtin_expect()來提供compiler分支預測
下面懶的翻了…反正就我們預測它比較可能為真就用likely
比較不會成立就用unlikely...