使用likely和unlikely 優化程式效能

2021-09-24 19:09:52 字數 1796 閱讀 1432

作用

likely unlikely是為編譯器提供對分支優化的提示,基本用於if-else的分支優化場景。if-else在彙編時會將else分支的命令生成跳轉語句(jmp),而跳轉會影響程式效能,所以如果大部分情況下都是else分支成立的話,程式每次都會執行跳轉,從而影響效率,使用likely和unlikely即可以告訴編譯器大部分情況下哪個分支更有可能成立,從而將該分支的語句編譯到前面,提高執行效率。

實現

likely和unlikely是通過巨集定義實現的:

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

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

gcc文件對__builtin_expect()的解釋如下:

-- built-in function: long __builtin_expect (long exp, long c)

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

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.

使用

舉個栗子?

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

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

int main(char *ar**, int argc)

注意,編譯時需要加 -o2選項

可以用objdump -s *** 來檢視彙編指令

使用unlikely()時,彙編指令為je(相等則跳轉)

而使用likely()時,彙編指令為jne (不相等則跳轉)

詳解likely和unlikely函式

在linux核心中likely和unlikely函式有兩種 只能兩者選一 實現方式,它們的實現原理稍有不同,但作用是相同的,下面將結合linux 2.6.38.8版本的核心 來進行講解。1 對 builtin expect的封裝 它們的源 如下 cpp view plain copy linux 2...

核心中的likely和unlikely巨集的使用

在核心 中經常會看到unlikely和likely的蹤影。他們實際上是定義在 linux compiler.h 中的兩個巨集。define likely x builtin expect x 1 define unlikely x builtin expect x 0 這裡的 built expec...

在linux中的likely和unlikely

在linux中的likely和unlikely 0 推薦 在linux中判斷語句經常會看到likely和unlikely,例如 if likely value else 簡單從表面上看if likely value if value if unlikely value if value 這兩個巨集對...