作用
likely unlikely为编译器提供了分支优化提示,基本上用于if-else的分支优化场景。 if-else在装配时会生成跳转语句(jmp )来指示else分支,但跳转会影响程序的性能,因此大多数情况下,一旦else分支成立,程序每次都会执行跳转以影响效率。 在大多数情况下,likely和unlikely允许编译器知道哪些分支很可能成立,并允许您在之前编译该分支的语句
实现
likely和unlikely是通过宏观定义实现的:
#definelikely(x ) __builtin_expect (! (x ),1 ) #defineunlikely(x ) __builtin_expect (! (x,0 )在GCC文档中,__builtin_expect )的说明如下:
- built-in function : long _ _ builtin _ expect (long exp,long C ) you may use ` _ builtin _ expect ' toprovidethecomping youshouldprefertouseactualprofilefeedbackforthis `-f profile-arcs ',asprogrammersarenotoriouslybadatpredictinghowtheingheirprprprotis thereareapplicationsinwhichthisdataishardtocollect.thereturnvalueisthevalueofexp, whichshouldbeanintegralexpression.thevalueofcmustbeacompile-time constant.thesemanticsofthebuilt-inarethatitexpectedthed wouldindicatethatwedonotexpecttocall ` foo ',sinceweexpect ` x ' tobe zero.sinceyouarelimitedtointegralexpressionsforexp=NULL,1 ) )错误); whentestingpointerorfloating-point values.http://www.Sina.com /
举栗吗?
#definelikely(x ) __builtin_expect (! (x ),1 ) #defineunlikely(x ) __builtin_expect (! (x ),0 ) intmain(char*argv[ ),int argc ) { int a;/* getthevaluefromsomewheregccan ' toptimize */a=atoi (argv [1]; 等同于if(unlikely(a==2) )//if (a==2) a; else a--; printf(%d(n ),a ); 返回0; }请注意,必须在编译时添加-O2选项
汇编指令可以在objdump -S XXX中查看
unlikely ) )时,集合命令为je (如果相等,则为跳转)
另一方面,likely ) )时,汇编指令为jne (如果不相等,则为跳转)
原文链接: https://www.Jian Shu.com/p/6822 E6 e8e2b 9