Chinaunix首页 | 论坛 | 博客
  • 博客访问: 578310
  • 博文数量: 353
  • 博客积分: 1104
  • 博客等级: 少尉
  • 技术积分: 1457
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-23 23:02
个人简介

1、刚工作时做Linux 流控;后来做安全操作系统;再后来做操作系统加固;现在做TCP 加速。唉!没离开过类Unix!!!但是水平有限。。

文章存档

2015年(80)

2013年(4)

2012年(90)

2011年(177)

2010年(1)

2009年(1)

分类:

2012-06-20 14:26:29


likely() 和 unlikely()两个宏定义在linux-2.6.24/include/linux/compiler.h (别的版本没看过)

  1. #define likely(x)   __builtin_expect(!!(x), 1)
  2. #define unlikely(x) __builtin_expect(!!(x), 0)

__builtin_expect是gcc中提供的一个预处理命令,用于代码优化。gcc(version 4.4.0)具体定义如下:

long __builtin_expect (long exp, long c) [Built-in Function]

注解为:
You may use __builtin_expect to provide the compiler with branch prediction information. In general, you should prefer to use actual profile feedback for this (‘-fprofile-arcs’), as programmers are notoriously bad at predicting how their programs actually perform. However, there are applications in which this data is hard to collect.The return value is the value of exp, which should be an integral expression. The semantics of the built-in are that it is expected that exp == c.

#define likely(x) __builtin_expect(!!(x), 1)
说明 x==1 是“很可能发生的”。这里的!!(x)是用来获取布尔值的。x若是6, !(x)为0  !!(x)就为1

使用likely(),执行if后面语句的可能性大些,编译器将if{}是的内容编译到前面,
使用unlikely(),执行else后面语句的可能性大些,编译器将else{}里的内容编译到前面。
这样有利于cpu预取,提高预取指令的正确率,因而可提高效率。likely与unlikely互换或不用都不会影响程序的正确性。但可能会影响程序的效率。


内核代码举例:文件 linux-2.6.24/drivers/ata/libata-core.c

  1. if (unlikely(ata_rwcmd_protocol(tf, dev) < 0))
  2.             return -EINVAL;


阅读(558) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~