星空网 > 软件开发 > 操作系统

gcc/linux内核中likely、unlikely和__attribute__(section())属性

查看linux内核源码,你会发现有很多if (likely(""))...及if (unlikely(""))...语句,这些语句其实是编译器的一种优化方式,具体分析如下:

likely及unlikely是一个宏定义:

#define likely(x)  __builtin_expect(!!(x), 1)

#define unlikely(x)  __builtin_expect(!!(x), 0)

 

likely()的 意思是认为这个分支最有可能发生,如if (likely(x == 0)){...},这个语句表示x等于0最有可能发生,其实语意就相当于if (x == 0){...},只不过likely针

对程序指令运行做了优化,不去做一些无谓的指令跳转;unlikely()意思相反,就是最不可能发生,注意if (unlikely(x == 0))还是相当于if (x==0)的逻辑。

 

如果需要更进一步了解likely()就必须要深入了解__bulitin_expect(!!(x), 1)函数。

— Built-in Function: 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 semantics of the built-in are that it is expected that exp == c. For example: if (__builtin_expect (x, 0)) foo (); indicates 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)) foo (*ptr); when testing pointer or floating-point values.

文档链接:https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#Other-Builtins

 

从gcc官方文档来看,内建函数long __builtin_expect (long exp, long c)主要用于优化程序的分支预测,减少程序的指令跳转,现代处理器一般都是流水线架构

很多芯片级的优化是靠流水线预取完成的,所以我们的程序优化也是需要尽量减少跳转。

 

文档也提到了由于大部分程序员根本就不了解自己程序的运行情况,所以推荐我们在编译时加上-fprofile-arcs选项去评估我们的程序分支运行情况;-fprofile-arcs选

项是代码覆盖率测试工具gcov使用时需要增加的编译选项,gcov能够去统计及分析我们的程序的分支运行情况,关于gcov的使用这里不做介绍,只需要知道gcov是

一个测试统计工具,配合-fprofile-arcs工具使用,__builtin_expect 根据gcov的分析结果来做实际的分支预测优化。

 

这里可以大家还会有疑问,为什么#define likely(x)  __builtin_expect(!!(x), 1)中要使用!!(x),这其实是因为函数__builtin_expect (long exp, long c)期望是exp == c,这时的1相当于bool值true,所以exp需要是一个bool表达式,通过!!可以变成bool表达式而不改变原有函数,这样才能够正确的与1或0(bool值)做匹配判断;试想如果没有!!,即#define likely(x)  __builtin_expect((x), 1),那么likely(10)原本是希望表达式是true,但是根据函数的处理逻辑10 != 1,那么优化会以false的结果来优化,这样就阴差阳错了!!!

 

 

最后讲述一下__attribute__(section(""))属性,这个属性比较好理解,就是为某个函数或变量指定section,比如:

int __attribute__(section(".test.data")) value = 0;

这样的话变量value将会被放在.test.data段中;

void __attribute__((section(".test.text"))) func(void){}

这样函数func会被放入.test.text段中。

 

查看section信息可以通过如下命令:readelf -S xxx,可以查看可执行文件也可以是目标文件.o,关于section这里不过多介绍,只要大概知道一般我们的代码都是放在.text段,全局变量一般放在.data段,我们通过__attribute__((""))定义的符号就放在我们特定的section里面。

 




原标题:gcc/linux内核中likely、unlikely和__attribute__(section())属性

关键词:linux

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流