用于优化代码执行效率,提高预读指令的命中率,避开跳转指令影响!
推荐 : https://my.oschina.net/moooofly/blog/175019
//g.c
// !!(x) 强制转成 bool型
#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;
}
int test(int x)
{
if((x))
{
x = 5;
}
else
{
x = 6;
}
return x;
}
//user:~$ gcc -fprofile-arcs -O2 -c g.c
//user:~$ objdump -d g.o
g.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <test_likely>:
0: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 8 <test_likely+0x8>
7: 01
8: 85 ff test %edi,%edi
a: b8 05 00 00 00 mov $0x5,%eax
f: 74 07 je 18 <test_likely+0x18>
11: f3 c3 repz retq
13: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
18: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 20 <test_likely+0x20>
1f: 01
20: b8 06 00 00 00 mov $0x6,%eax
25: c3 retq
26: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
2d: 00 00 00
0000000000000030 <test_unlikely>:
30: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 38 <test_unlikely+0x8>
37: 01
38: 85 ff test %edi,%edi
3a: 75 14 jne 50 <test_unlikely+0x20>
3c: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 44 <test_unlikely+0x14>
43: 01
44: b8 06 00 00 00 mov $0x6,%eax
49: c3 retq
4a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)
50: b8 05 00 00 00 mov $0x5,%eax
55: c3 retq
56: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
5d: 00 00 00
0000000000000060 <test>:
60: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 68 <test+0x8>
67: 01
68: 85 ff test %edi,%edi
6a: b8 05 00 00 00 mov $0x5,%eax
6f: 75 0d jne 7e <test+0x1e>
71: 48 83 05 00 00 00 00 addq $0x1,0x0(%rip) # 79 <test+0x19>
78: 01
79: b8 06 00 00 00 mov $0x6,%eax
7e: f3 c3 repz retq
Disassembly of section .text.startup:
0000000000000000 <_GLOBAL__sub_I_65535_0_test_likely>:
0: bf 00 00 00 00 mov $0x0,%edi
5: e9 00 00 00 00 jmpq a <_GLOBAL__sub_I_65535_0_test_likely+0xa>
参考:
https://blog.csdn.net/grublinux/article/details/37543489
https://blog.csdn.net/u013139008/article/details/83384384