简体   繁体   中英

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.

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.

在“6.2.2优化1级指令高速缓存访​​问”下查看每个程序员应该了解的内存 - 这里有一个部分。

可能的(),并不太可能()宏在内核头文件中定义的东西漂亮的名字这一个真正的GCC功能

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM