Linux内核中的likely和unlikely


    今天同事问我内核中likely()和unlikely()实现机理。我当时说这是Linux内核使用gcc编译器进行条件分支优化,具体细节没有深究。

   晚上回来查看内核源码和google,进一步认识了这两个宏作用。

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


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

   kernel里面的定义:

#ifndef __LINUX_COMPILER_H
#define __LINUX_COMPILER_H

/* Somewhere in the middle of the GCC 2.96 development cycle, we implemented
    a mechanism by which the user can annotate likely branch directions and
    expect the blocks to be reordered appropriately.   Define __builtin_expect
    to nothing for earlier compilers.   */

#if __GNUC__ == 2 && __GNUC_MINOR__ < 96
#define __builtin_expect(x, expected_value) (x)
#endif

#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)

#endif /* __LINUX_COMPILER_H */


可以看到在2.96以前版本中,gcc并没有实现lilely和unlikely。在gcc以后版本中,__builtin_expect是gcc的内置函数。

--- end ---

相关内容