views:

243

answers:

3

I came across these 2 macros in Linux kernel code. I know they are instructions to compiler (gcc) for optimizations in case of branching. My question is, can we use these macros in user space code? Will it give any optimization? Any example will be very helpful.

+3  A: 

The likely() and unlikely() macros are pretty names defined in the kernel headers for something that is a real gcc feature

Ken Bloom
+4  A: 

Yes they can. In the Linux kernel, they are defined as

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

The __builtinexpect macros are GCC specific macros that use the branch prediction; they tell the processor whether a condition is likely to be true, so that the processor can prefetch instructions on the correct "side" of the branch.

You should wrap the defines in an ifdef to ensure compilation on other compilers:

#ifdef __GNUC__
#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)
#else
#define likely(x)       (x)
#define unlikely(x)     (x)
#endif

It will definitely give you optimizations if you use it for correct branch predictions.

Tomas
In the #else part, shouldn't they evaluate to (x) and not empty?
Laurynas Biveinis
oops, yes of course. Edited
Tomas
which header file contains this definition in user include directories ?
vinit dhatrak
@vinit: http://lxr.linux.no/linux+v2.6.31/include/linux/compiler.h#L138
tonfa
@tonfa i dont want kernel's header file. I want file which is in /usr/include so that I can include it in my user space code.
vinit dhatrak
They are only available in the kernels header file (or maybe in other projects). I suggest you create your own header file and add the definitions above. __builtin_expect is a gcc builtin and doesn't need an addition header file.
Tomas
A: 

Take a look into What Every Programmer Should Know About Memory under "6.2.2 Optimizing Level 1 Instruction Cache Access" - there's a section about exactly this.

Nikolai N Fetissov
@Nikolai Thank you for the link.
vinit dhatrak
No problem. This is a very enlightening paper, even on a third read :)
Nikolai N Fetissov