轉自http://blog.csdn.net/rstevens/archive/2007/09/24/1798561.aspx
在 2.6 內核中,隨處可以見到 likely() 和 unlikely() 的身影,那么為什么要用它們?它們之間有什么區別?
首先要明確:
if(likely(value)) 等價于 if(value)
if(unlikely(value)) 也等價于 if(value)
也就是說 likely() 和 unlikely() 從閱讀和理解代碼的角度來看,是一樣的!!!
這兩個宏在內核中定義如下:
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
__builtin_expect() 是 GCC (version >= 2.96)提供給程序員使用的,目的是將“分支轉移”的信息提供給編譯器,這樣編譯器可以對代碼進行優化,
以減少指令跳轉帶來的性能下降。__builtin_expect((x),1) 表示 x 的值為真的可能性更大;
__builtin_expect((x),0) 表示 x 的值為假的可能性更大。
也就是說,使用 likely() ,執行 if 后面的語句 的機會更大,使用unlikely(),執行else 后面的語句的機會更大。
例如下面這段代碼,作者就認為 prev 不等于 next 的可能性更大,
if (likely(prev != next)) {
next->timestamp = now;
...
} else {
...;
}
通過這種方式,編譯器在編譯過程中,會將可能性更大的代碼緊跟著起面的代碼,從而減少指令跳轉帶來的性能上的下降。
下面以兩個例子來加深這種理解:
第一個例子: example1.c
int testfun(int x)
{
if(__builtin_expect(x, 0)) {
^^^--- We instruct the compiler, "else" block is more probable
x = 5;
x = x * x;
} else {
x = 6;
}
return x;
}
在這個例子中,我們認為 x 為0的可能性更大
編譯以后,通過 objdump 來觀察匯編指令,在我的 2.4 內核機器上,結果如下:
# gcc -O2 -c example1.c
# objdump -d example1.o
Disassembly of section .text:
00000000 <testfun>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 85 c0 test %eax,%eax
8: 75 07 jne 11 <testfun+0x11>
a: b8 06 00 00 00 mov $0x6,%eax
f: c9 leave
10: c3 ret
11: b8 19 00 00 00 mov $0x19,%eax
16: eb f7 jmp f <testfun+0xf>
可以看到,編譯器使用的是 jne (不相等跳轉)指令,并且 else block 中的代碼緊跟在后面。
8: 75 07 jne 11 <testfun+0x11>
a: b8 06 00 00 00 mov $0x6,%eax
第二個例子: example2.c
int testfun(int x)
{
if(__builtin_expect(x, 1)) {
^^^ --- We instruct the compiler, "if" block is more probable
x = 5;
x = x * x;
} else {
x = 6;
}
return x;
}
在這個例子中,我們認為 x 不為 0 的可能性更大
編譯以后,通過 objdump 來觀察匯編指令,在我的 2.4 內核機器上,結果如下:
# gcc -O2 -c example2.c
# objdump -d example2.o
Disassembly of section .text:
00000000 <testfun>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 85 c0 test %eax,%eax
8: 74 07 je 11 <testfun+0x11>
a: b8 19 00 00 00 mov $0x19,%eax
f: c9 leave
10: c3 ret
11: b8 06 00 00 00 mov $0x6,%eax
16: eb f7 jmp f <testfun+0xf>
這次編譯器使用的是 je (相等跳轉)指令,并且 if block 中的代碼緊跟在后面。
8: 74 07 je 11 <testfun+0x11>
a: b8 19 00 00 00 mov $0x19,%eax