如下是一个实际的例子。
//test_builtin_expect.c
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
int test_likely(int x)
{
if(LIKELY(x))
{
x = 5;
}
else
{
x = 6;
}
return x;
}
int test_unlikely(int x)
{
if(UNLIKELY(x))
{
x = 5;
}
else
{
x = 6;
}
return x;
}
:
00 push %ebp
01 mov %esp,%ebp
03 mov 0x8(%ebp),%eax
06 addl $0x1,0x38
0d adcl $0x0,0x3c
14 test %eax,%eax
16 jz 2d //主要看这里。此处的效果是eax不为零时,不需要跳转。即x为真是不跳转。
18 addl $0x1,0x40
1f mov $0x5,%eax
24 adcl $0x0,0x44
2b pop %ebp
2c ret
2d addl $0x1,0x48
34 mov $0x6,%eax
39 adcl $0x0,0x4c
40 pop %ebp
41 ret
42 lea 0x0(%esi,%eiz,1),%esi
49 lea 0x0(%edi,%eiz,1),%edi
:
50 push %ebp
51 mov %esp,%ebp
53 mov 0x8(%ebp),%edx
56 addl $0x1,0x20
5d adcl $0x0,0x24
64 test %edx,%edx
66 jne 7d //主要看这里。此处的效果是edx为零时,不需跳转。即x为假时不跳转。
68 addl $0x1,0x30
6f mov $0x6,%eax
74 adcl $0x0,0x34
7b pop %ebp
7c ret
7d addl $0x1,0x28
84 mov $0x5,%eax
89 adcl $0x0,0x2c
90 pop %ebp
91 ret
92 lea 0x0(%esi,%eiz,1),%esi
99 lea 0x0(%edi,%eiz,1),%edi
参考资料:http://hi.baidu.com/uu_dou/item/e9f6f41d570d817b7a5f25c7