Linux内核中的likely与unlikely

栏目: 服务器 · Linux · 发布时间: 6年前

内容简介:likely() 和 unlikely()两个宏定义在linux-2.6.24/include/linux/compiler.h (别的版本没看过)__builtin_expect是gcc中提供的一个预处理命令,用于代码优化。gcc(version 4.4.0)具体定义如下:long __builtin_expect (long exp, long c) [Built-in Function]

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 ;

以上所述就是小编给大家介绍的《Linux内核中的likely与unlikely》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

论因特网

论因特网

[美] 休伯特·L.德雷福斯 / 喻向午、陈硕 / 河南大学出版社 / 2015-5 / 32.00

本书是与日俱增的关于因特网利弊之文献的重要补充。 ——《哲学评论》 关于因特网种种承诺的一次清晰辨析……以哲学家的眼光审视一个影响我们所有人的问题。 ——《普遍存在》杂志 ……一场精心设计的论战……我们需要更多德雷福斯这样的老师,将网络融入依 然具有深邃人性的课程。 ——亚当•莫顿(出自《泰晤士报文学增刊》) 在互联网世界,不管你是菜鸟,还是浸淫其中已久—......一起来看看 《论因特网》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具