转载:Kernel : likely/unlikely macros

看内核的时候发现unlikely这个函数看不懂,一找,找到一个不错的帖子。
这两个函数实际上就是告诉编译器,怎么样优化程序。likely()的结果非常大的可能性是真,而unlikely的结果极大概率为假。
下面是原文:
 
 
 
 
Posted by Kedar Sovani on Friday, February 11, 2005 - 04:46   @ KernelTrap.org

Ever wondered what the likely and unlikely macros in the linux kernel are ?

The macros are defined as :

#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)

The __builtin_expect is a method that gcc (versions >= 2.96) offer for programmers to indicate branch prediction information to the compiler. The return value of __builtin_expect is the first argument (which could only be an integer) passed to it.

To check it out how it could be beneficial, an excerpt from "info gcc" :

if (__builtin_expect (x, 0))
foo ();


[This] would indicate that we do not expect to call `foo', since we
expect `x' to be zero.

 

Based on this information the compiler generates intelligent code, such that the most expected result is favored.
 


Let us consider it with a simple example function :

 

[kedar@ashwamedha ~]$ cat abc.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;
}

 

[kedar@ashwamedha ~]$ gcc -O2 -c abc.c
[kedar@ashwamedha ~]$ objdump -d abc.o

abc.o: file format elf32-i386

Disassembly of section .text:

00000000 :
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 >
^^^ --- The compiler branches the "if" block and keeps "else" sequential
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 >

And let us see what happens if we make the "if" block more likely.

[kedar@ashwamedha ~]$ cat abc.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;
}

 

[kedar@ashwamedha ~]$ gcc -O2 -c abc.c
[kedar@ashwamedha ~]$ objdump -d abc.o

abc.o: file format elf32-i386

Disassembly of section .text:

00000000 :
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 >
^^^ --- The compiler branches the "else" block and keeps "if" sequential
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 >

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值