有关likely和unlikely

来源:互联网 发布:linux怎么编程 编辑:程序博客网 时间:2024/04/26 12:03
 

================================

Author: taoyuetao
Email: tao_yuetao@yahoo.com.cn
Blog: taoyuetao.cublog.cn

================================

linux中判断语句经常会看到likely和unlikely,例如:

if(likely(value)){

}

else{

}

简单从表面上看if(likely(value)) == if(value),if(unlikely(value)) == if(value)。

也就是likely和unlikely是一样的,但是实际上执行是不同的,加likely的意识是value的值为真的可能

性更大一些,那么执行if的机会大,而unlikely表示value的值为假的可能性大一些,执行else机会大一些。

加上这种修饰,编译成二进制代码时likely使得if后面的执行语句紧跟着前面的程序,unlikely使得else后

面的语句紧跟着前面的程序,这样就会被cache预读取,增加程序的执行速度,likely和unlikely的实现在

include/linux/compiler.h中:

      9 #if __GNUC__ == 2 && __GNUC_MINOR__ < 96
     10 #define __builtin_expect(x, expected_value) (x)
     11 #endif
     12
     13 #define likely(x)   __builtin_expect((x),1)
     14 #define unlikely(x) __builtin_expect((x),0)

__builtin_expect是gcc的一个预处理命令,其解释如下:

long __builtin_expect (long exp, long c)
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
value of c must be a compile-time constant. The semantics of the built-in are that it
is expected that exp == c. For example:
if (__builtin_expect (x, 0))
foo ();
would indicate that we do not expect to call foo, since we expect x to be zero. Since
you are limited to integral expressions for exp, you should use constructions such as
if (__builtin_expect (ptr != NULL, 1))
error ();
when testing pointer or floating-point values.

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 绿地珊瑚蕨干了怎么办 翠云草叶子蔫了怎么办 珊瑚蕨叶子烂了怎么办 黑骨茶叶子黑斑怎么办 外场主持没有人互动怎么办 企业年报填错了怎么办 手机忘了放哪了怎么办 燃气卡车没气了怎么办 老房子拆了重建怎么办 加了差的汽油怎么办 事业单位未满5年怎么办 小学孩子不会制订学习计划怎么办 忘记提交原创怎么办百度熊掌号 计算机一级报名表填错了怎么办 离婚了不给孩子生活费怎么办 点击爱奇艺系统提示停止运行怎么办 电视机图像颜色变了怎么办 10万签约被拒怎么办 钢琴弹奏中的折指怎么办! 吉他琴头旋钮将琴头扭坏了怎么办? 1岁幼儿不爱吃饭怎么办 3岁幼儿不爱吃饭怎么办 4岁幼儿不爱吃饭怎么办 买票买了点映 怎么办 一年级孩子注意力不集中怎么办 孩子上一年级注意力不集中怎么办 普宁二中初一新生住宿怎么办 小学入学普查错过了怎么办 初一的孩子不爱学习怎么办 初一孩子出现厌学情况怎么办 客人要求我们代办事项时怎么办 客人要求我们代办事项应该怎么办 想家了特别想哭怎么办 把友谊看得太重怎么办 高一新生数学差怎么办 如果好朋友觉得你成熟阴暗怎么办 被同学抓住把柄敲诈怎么办 初一学生字写的不好怎么办 初二学生字写不好怎么办 宝宝流鼻涕怎么办最简单方法 论文查重中参考文献重复率高怎么办