Is it likely(), or unlikely()?

1. December 2008

This post is relatively off-topic compared to my other posts on C# and .net but I see a value behind it, so decided to blog about it.

While I have been dealing with my assignment on linux system calls, I have seen something interesting. There were 2 macros in use for condition evaluation: likely(condition) or unlikely(condition). This is a compiler optimization used in linux kernel and it isn’t meant to be used in normal applications. It is even useless in ordinary applications. However, this is definitely not the case for an OS kernel where even a single instruction for performance matters.

Now, how does this work? What is the magic behind it?

When we take a look at the definition of likely and unlikely macros we see

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

I didn’t know about __builtin_expect, so I searched for it and reached that page.

It says that this call can be used to provide the compiler with branch prediction information and the compiler uses it to produce optimized assembly code. Something had appeared in my head, I wonder if there was more magic going on so I gave it a go.

int test_likely(int c)
{
    if(__builtin_expect(c,1))
    {
        c++;
    }
    else
    {
        c=1
    }
    return c;
}

This code yielded in the following assembly code

image

And for unlikely,

int test_unlikely(int c)
{
    if(__builtin_expect(c,0))
    {
        c++;
    }
    else
    {
        c=1
    }
    return c;
}

compiler produces

image

Do you see the difference? On line 13(d), we see that it executes jne or je instruction. If the condition is likely to happen, it doesn’t branch and executes the code under if, otherwise branch to else. If the condition is unlikely to happen, it keeps else close to the code, since else block is likely to be executed.

Those kind of optimizations should be used as a last resort. In most applications, you don’t even need such optimizations, you should concentrate on bottlenecks instead, such as network traffic etc.

I’d like to end this post with the quote I already said:

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” (Donald Knuth)

, ,