Linux内核中可能的()和不太可能的()宏如何工作以及它们的好处是什么? [英] How do the likely() and unlikely() macros in the Linux kernel work and what is their benefit?

查看:140
本文介绍了Linux内核中可能的()和不太可能的()宏如何工作以及它们的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 如果(不太可能( fd <0))
{
/ *做某事* /
}

 如果(可能(!err))
{
/ * * /
}

我找到了它们的定义:

  #define likely(x)__builtin_expect((x),1)
#define impossible(x)__builtin_expect((x), 0)

我知道他们是为了优化,但他们是如何工作的?使用它们可以预期性能/尺寸会下降多少?至少在瓶颈代码中(当然是在用户空间中),它是否值得麻烦(并且可能会丢失可移植性)。 解决方案

>它们暗示编译器发出的指令会导致分支预测支持跳转指令的可能一侧。这可能是一个很大的胜利,如果预测是正确的,这意味着跳转指令基本上是空闲的,并且将需要零周期。另一方面,如果预测是错误的,那么意味着处理器流水线需要刷新并且可能花费几个周期。只要预测在大多数时候都是正确的,那么这对性能就会有好处。



像所有这些性能优化一样,只有在广泛分析后才能做到这一点确保代码真的处于瓶颈状态,并且可能给出了微观性质,它正在紧密循环中运行。一般来说,Linux开发人员都非常有经验,所以我想他们会这样做。他们并不太关心可移植性,因为他们只是针对gcc,他们对他们希望产生的程序集非常了解。


I've been digging through some parts of the Linux kernel, and found calls like this:

if (unlikely(fd < 0))
{
    /* Do something */
}

or

if (likely(!err))
{
    /* Do something */
}

I've found the definition of them:

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

I know that they are for optimization, but how do they work? And how much performance/size decrease can be expected from using them? And is it worth the hassle (and losing the portability probably) at least in bottleneck code (in userspace, of course).

解决方案

They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.

Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.

这篇关于Linux内核中可能的()和不太可能的()宏如何工作以及它们的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆