Can likely/unlikely macros be used in user-space code?

后端 未结 3 438
南笙
南笙 2020-12-14 07:35

I came across these 2 macros in Linux kernel code. I know they are instructions to compiler (gcc) for optimizations in case of branching. My question is, can we use these ma

相关标签:
3条回答
  • 2020-12-14 08:15

    Take a look into What Every Programmer Should Know About Memory under "6.2.2 Optimizing Level 1 Instruction Cache Access" - there's a section about exactly this.

    0 讨论(0)
  • 2020-12-14 08:18

    The likely() and unlikely() macros are pretty names defined in the kernel headers for something that is a real gcc feature

    0 讨论(0)
  • 2020-12-14 08:26

    Yes they can. In the Linux kernel, they are defined as

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

    The __builtin_expect macros are GCC specific macros that use the branch prediction; they tell the processor whether a condition is likely to be true, so that the processor can prefetch instructions on the correct "side" of the branch.

    You should wrap the defines in an ifdef to ensure compilation on other compilers:

    #ifdef __GNUC__
    #define likely(x)       __builtin_expect(!!(x), 1)
    #define unlikely(x)     __builtin_expect(!!(x), 0)
    #else
    #define likely(x)       (x)
    #define unlikely(x)     (x)
    #endif
    

    It will definitely give you optimizations if you use it for correct branch predictions.

    0 讨论(0)
提交回复
热议问题