Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can likely/unlikely macros be used in user-space code?

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.

like image 335
Vinit Dhatrak Avatar asked Nov 03 '09 15:11

Vinit Dhatrak


People also ask

What is the use of likely and unlikely macros in Linux kernel?

A look at the Linux kernel code will show many if conditions enclosed in likely and unlikely macros. These macros invoke compiler directives that give the compiler a hint on the code leg that should be optimized for performance.

When to use unlikely in C?

C++ attribute: likely, unlikely (since C++20) 1) Applies to a statement to allow the compiler to optimize for the case where paths of execution including that statement are more likely than any alternative path of execution that does not include such a statement.

What is __ Builtin_expect?

You can use the __builtin_expect built-in function to indicate that an expression is likely to evaluate to a specified value. The compiler can use this knowledge to direct optimizations. This built-in function is portable with the GNU C/C++ __builtin_expect function.


1 Answers

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 __builtin_expect 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.

like image 52
Tomas Avatar answered Oct 08 '22 22:10

Tomas