简体   繁体   English

可能/不太可能的宏可用于用户空间代码吗?

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

I came across these 2 macros in Linux kernel code. 我在Linux内核代码中遇到了这两个宏。 I know they are instructions to compiler (gcc) for optimizations in case of branching. 我知道它们是编译器(gcc)的指令,用于在分支的情况下进行优化。 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 在Linux内核中 ,它们被定义为

#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; __builtin_expect宏是使用分支预测的GCC特定宏; 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中以确保在其他编译器上进行编译:

#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功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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