2011年2月24日星期四

likely() & unlikely() in Linux kernel

 在kernel中的定义:
#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)


The __builtin_expect is a method that gcc (versions >= 2.96) offer for programmers to indicate branch prediction information to the compiler. The return value of __builtin_expect is the first argument (which could only be an integer) passed to it.


likely和unlikely是用来编译优化的, 只和编译器有关,其实都可以没有。我们知道很多cpu里面有告诉缓存,且有预读机制,likely和unlikely就是增加执行判断语句时的命中率。


   如果是if(lilely(a)),说明a条件发生的可能性大,那么a为真的语句在编译成二进制的时候就应该紧跟在前面程序的后面,这样就会被cache预读取进去,增加程序执行速度。 unlikely则是正好相反。


Ref: http://kerneltrap.org/node/4705
http://www.linuxidc.com/Linux/2009-12/23496.htm

没有评论:

发表评论