How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

后端 未结 10 851
攒了一身酷
攒了一身酷 2020-11-22 12:58

I\'ve been digging through some parts of the Linux kernel, and found calls like this:

if (unlikely(fd < 0))
{
    /* Do something */
}

o

10条回答
  •  借酒劲吻你
    2020-11-22 13:25

    long __builtin_expect(long EXP, long C);
    

    This construct tells the compiler that the expression EXP most likely will have the value C. The return value is EXP. __builtin_expect is meant to be used in an conditional expression. In almost all cases will it be used in the context of boolean expressions in which case it is much more convenient to define two helper macros:

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

    These macros can then be used as in

    if (likely(a > 1))
    

    Reference: https://www.akkadia.org/drepper/cpumemory.pdf

提交回复
热议问题