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
2009-11-03 15:30:33
+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
2009-11-03 15:32:04
In the #else part, shouldn't they evaluate to (x) and not empty?
Laurynas Biveinis
2009-11-03 15:33:50
oops, yes of course. Edited
Tomas
2009-11-03 15:35:43
which header file contains this definition in user include directories ?
vinit dhatrak
2009-11-03 15:40:05
@vinit: http://lxr.linux.no/linux+v2.6.31/include/linux/compiler.h#L138
tonfa
2009-11-03 15:43:57
@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
2009-11-03 15:46:15
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
2009-11-03 16:52:59
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
2009-11-03 15:38:46
No problem. This is a very enlightening paper, even on a third read :)
Nikolai N Fetissov
2009-11-03 18:31:34