Linux宏之likely/unlikely
这两个宏在内核中定义如下:
1 #define likely(x) __builtin_expect((x),1) 2 #define unlikely(x) __builtin_expect((x),0)
__builtin_expect() 是 GCC (version >= 2.96)提供给程序员使用的,目的是将“分支转移”的信息提供给编译器,这样编译器可以对代码进行优化,以减少指令跳转带来的性能下降。编译器会根据可能性大小,把非跳转代码紧跟在if之前的代码后面,而把跳转代码放到可能性小的位置。
__builtin_expect((x),1) 表示 x 的值为真的可能性更大;
__builtin_expect((x),0) 表示 x 的值为假的可能性更大。
也就是说,使用 likely() ,执行 if 后面的语句 的机会更大,使用unlikely(),执行else 后面的语句的机会更大。
例如下面这段代码,作者就认为 prev 不等于 next 的可能性更大,
1 if (likely(prev != next)) { 2 next->timestamp = now; 3 ... 4 } else { 5 ...; 6 }
通过这种方式,编译器在编译过程中,会将可能性更大的代码紧跟着起面的代码,从而减少指令跳转带来的性能上的下降。
下面以两个例子来加深这种理解:
第一个例子: example1.c
1 int testfun(int x) 2 { 3 if(__builtin_expect(x, 0)) { 4 x = 5; 5 x = x * x; 6 } else { 7 x = 6; 8 } 9 return x; 10 }
在这个例子中,我们认为 x 为0的可能性更大
编译以后,通过 objdump 来观察汇编指令,在我的 2.4 内核机器上,结果如下:
# gcc -O2 -c example1.c
# objdump -d example1.o
1 Disassembly of section .text: 2 3 00000000 <testfun>: 4 55 push %ebp 5 89 e5 mov %esp,%ebp 6 8b 45 08 mov 0x8(%ebp),%eax 7 85 c0 test %eax,%eax 8 75 07 jne 11 <testfun+0x11> 9 b8 06 00 00 00 mov $0x6,%eax 10 c9 leave 11 c3 ret 12 b8 19 00 00 00 mov $0x19,%eax 13 eb f7 jmp f <testfun+0xf>
可以看到,编译器使用的是 jne (不相等跳转)指令,并且 else block 中的代码紧跟在后面。
1 75 07 jne 11 <testfun+0x11> 2 b8 06 00 00 00 mov $0x6,%eax
第二个例子: example2.c
1 int testfun(int x) 2 { 3 if(__builtin_expect(x, 1)) { 4 5 x = 5; 6 x = x * x; 7 } else { 8 x = 6; 9 } 10 return x; 11 }
在这个例子中,我们认为 x 不为 0 的可能性更大
编译以后,通过 objdump 来观察汇编指令,在我的 2.4 内核机器上,结果如下:
# gcc -O2 -c example2.c
# objdump -d example2.o
1 Disassembly of section .text: 2 3 00000000 <testfun>: 4 55 push %ebp 5 89 e5 mov %esp,%ebp 6 8b 45 08 mov 0x8(%ebp),%eax 7 85 c0 test %eax,%eax 8 74 07 je 11 <testfun+0x11> 9 b8 19 00 00 00 mov $0x19,%eax 10 c9 leave 11 c3 ret 12 b8 06 00 00 00 mov $0x6,%eax 13 eb f7 jmp f <testfun+0xf>
这次编译器使用的是 je (相等跳转)指令,并且 if block 中的代码紧跟在后面。
1 74 07 je 11 <testfun+0x11> 2 b8 19 00 00 00 mov $0x19,%eax

浙公网安备 33010602011771号