Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What is the between likely and unlikely calls in Kernel. While searching through the kernel source i found these statements.

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

Could somebody shed some light into it?

share|improve this question
    
This is really a programming question, better suited for Stack OVerflow. –  Gilles Apr 19 '11 at 20:17
add comment

1 Answer

up vote 5 down vote accepted

They are compiler hints for GCC. They're used in conditionals to tell the compiler if a branch is likely to be taken or not. It can help the compiler laying down the code in such a way that's optimal for the most frequent outcome.

They are used like this:

if (likely(some_condition)) {
  // the compiler will try and make the code layout optimal for the case
  // where some_condition is true, i.e. where this block is run
  most_likely_action();
} else {
  // this block is less frequently used
  corner_case();
}

It should be used with great care (i.e. based on actual branch profiling results). A wrong hint can degrade performance (obviously).

Some examples of how the code can be optimized are easily found by searching for GCC __builtin_expect. This blog post gcc optimisation: __builtin_expect for example details a disassembly with it.

The kind of optimizations that can be done is very processor-specific. The general idea is that often, processors will run code faster if it does not branch/jump all over the place. The more linear it is, and the more predictable the branches are, the faster it will run. (This is especially true for processors with deep pipelines for example.)

So the compiler will emit the code such that the most likely branch will not involve a jump if that's what the target CPU prefers, for instance.

share|improve this answer
    
What is meant by unicorns? Is it a technical term or just a filler? –  Sen Apr 19 '11 at 8:03
    
I removed the unicorns to avoid confusion. –  Mat Apr 19 '11 at 8:05
    
Could you please elaborate on the compiler will try and make the code layout optimal for the case? I would like to know how it does that. –  Sen Apr 19 '11 at 8:08
    
added a bit of information on that. there is no general way of optimizing code, it's all very processor dependent. –  Mat Apr 19 '11 at 8:19
    
Thanks Mat. I understood it well. –  Sen Apr 19 '11 at 10:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.