title: How do the likely/unlikely macros in the Linux kernel work and what is their benefit?
body: <p>I've been digging through some parts of the Linux kernel, and found calls like this:</p>
  
  <pre><code>if (unlikely(fd &lt; 0))
  {
      /* Do something */
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>if (likely(!err))
  {
      /* Do something */
  }
  </code></pre>
  
  <p>I've found the definition of them:</p>
  
  <pre><code>#define likely(x)       __builtin_expect((x),1)
  #define unlikely(x)     __builtin_expect((x),0)
  </code></pre>
  
  <p>I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).</p>