1. 程式人生 > >linux中的likely和unlikely

linux中的likely和unlikely

文章來源:http://blog.csdn.net/tommy_wxie/article/details/7384641

看核心時總遇到if(likely( )){}或是if(unlikely( ))這樣的語句,最初不解其意,現在有所瞭解,所以也想介紹一下。

likely() 與 unlikely()是核心(我看的是2.6.22.6版本,2.6的版本應該都有)中定義的兩個巨集。位於/include/linux/compiler.h中,
具體定義如下:
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)

__builtin_expect是gcc(版本>=2.96,網上寫的,我沒驗證過)中提供的一個預處理命令(這個名詞也是網上寫的,我想叫函式更好些),有利於程式碼優化。gcc(version 4.4.0)具體定義如下:
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 semantics of the built-in are that it is expected that exp == c.

它的意思是:我們可以使用這個函式人為告訴編繹器一些分支預測資訊“exp==c” 是“很可能發生的”。

#define likely(x) __builtin_expect(!!(x), 1)也就是說明x==1是“經常發生的”或是“很可能發生的”。
使用likely ,執行if後面語句的可能性大些,編譯器將if{}是的內容編譯到前面, 使用unlikely ,執行else後面語句的可能性大些,編譯器將else{}裡的內容編譯到前面。這樣有利於cpu預取,提高預取指令的正確率,因而可提高效率。

舉個例子(核心版本2.6.22.6):/kernel/shed.c中有一段:
if (likely(!active_balance)) {
/* We were unbalanced, so reset the balancing interval */
sd->balance_interval = sd->min_interval;
} else {
/*
* If we've begun active balancing, start to back off. This
* case may not be covered by the all_pinned logic if there
* is only 1 task on the busy runqueue (because we don't call
* move_tasks).
*/
if (sd->balance_interval max_interval)
sd->balance_interval *= 2;
}

編譯過程中,會將if後面{}裡的內容編譯到前面,else 後面{}裡的內容編譯到後面。若將likely換成unlikely 則正好相反。