likely, unlikely in Linux

likely and unlikely

You would have seen "likely" and "unlikely" macros in Linux kernels, modules or other programs. What are the macros doing? How do I properly use them?

kernel newbies – FAQ/LikelyUnlikely

Please visit kernel newbies' FAQ, it'll give you more detail and correct information.

compiler.h

The macros live in compiler.h, and looks pretty simple.

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

What is the expected behavior?

likely and unlikely does nothing to do with program logic. This means that you don't need to change the conditions due to likely and unlikely.

__builtin_expect(long EXP, long c)

Programs do prefetching following commands. When it sees a branch it follows the prediction information. So, if the prediction is wrong, it should discard the prefetched commands. Here you can give an information that this EXP will be true almost times or vice versa. This enables programs do a right prediction and enhances the performance.

Example

<code>// Let&#39;s say we have a do_something() function that returns 1 when succeed.
// And you expect that it succeeds for happy cases (most of the time)
// You can utilize likely
if (likely(do_something())) {
   // Do happy logics
}

// Or you may love this more
if (unlikely(do_something())) {
    // Computer can expect that this part will not be executed mostly, and it can prefetching the out of this if statement (or else part).
}
</code>

Comments

comments