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

别说谁变了你拦得住时间么 提交于 2019-11-28 21:12:31
Tomas

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!