在讀 Linux Permier 中文版的時候. Page 2-41 有一段
使用 likely() 與 unlikely() 巨集透過編譯器告知 CPU 有哪些程式區段不需要預測(likely)或有哪些程式區段需要預測(unlikely).
我對這一段有些懷疑, 為什麼要這樣做? 上網做了一下功課.
對映原始的 define
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
這是使用 GCC 內的特殊 Function, 可以查 GCC Document
– 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
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 asif (__builtin_expect (ptr != NULL, 1))
error ();when testing pointer or floating-point values.
簡單的說,
if(likely(x)){
預期想執行的 Code
}else{
}if(unlikely(x)){
}else{
預期想執行的 Code
}
這樣就可以利用 Compile 本身的功能最佳化 Processor 的 Pipeline (用 Branch Prediction)
在 x86 上是有用的.
不過我手上的 ARM Crosscompile 沒有一版可以產生不同結果的 Code.
不確定是因為 ARM9 不支援, 還是有其他因素.
Ref.
FAQ/LikelyUnlikely
Kernel : likely/unlikely macros
[Tags] Linux , Kernel , Marco, Likely, Unlikely [/Tags]
Tags: Linux




2 responses so far ↓
jsli // Feb 1, 2007 at 10:40 pm
Mozilla Firefox 2. on
Windows XP
Using
現在手邊沒有 cross-compiler 可以試,不過 ARM 的 instruction set 有 conditional execution 的 flag, 可以取代部份的 branch, 再加上 ARM9 5-stage pipeline 和相對較小的 cache, Branch prediction 就沒那麼重要了。Branch prediction 通常是為了避免 pipeline stall 和 cache miss penalty, 這部份 x86 要嚴重多了。
[reply this comment]
Anonymous // Aug 1, 2007 at 4:32 pm
Internet Explorer 6.0 on
Windows XP
Using
最后结论说反了吧
[reply this comment]
Leave a Comment