likely && unlikely

likely和unlikely是gcc擴展的跟處理器相關的宏:

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


現在處理器都是流水線的,有些裏面有多個邏輯運算單元,系統可以提前取多條指令進行並行處理,但遇到跳轉時,則需要重新取指令,這相對於不用重新去指令就降低了速度。所以就引入了likely和unlikely,目的是增加條件分支預測的準確性,cpu會提前裝載後面的指令,遇到條件轉移指令時會提前預測並裝載某個分支的指令。unlikely 表示你可以確認該條件是極少發生的,相反likely表示該條件多數情況下會發生。編譯器會產生相應的代碼來優化cpu執行效率。
因此程序員在編寫代碼時可以根據判斷條件發生的概率來優化處理器的取指操作。

 從表面上看if(likely(value)) == if(value),if(unlikely(value)) == if(value)

 內核2.2.26的頭文件include/linux/compiler.h中有宏定義

/*
 * Generic compiler-dependent macros required for kernel
 * build go below this comment. Actual compiler/compiler version
 * specific implementations come from the above header files
 */

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


 __builtin_expect是gcc的一個預處理命令,其解釋如下:

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 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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章