這兩個宏對程式運作結果沒有影響,隻是用于提高程式效率。其實作和gcc編譯器密切相關。 具體點說,就是如果你覺得程式運作時候一般param = 0的可能性比較大,那麼就加上likely的macro;反之則加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 |