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

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

问题描述

我一直在挖掘 Linux 内核的某些部分,发现了这样的调用:

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

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

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

我找到了它们的定义:

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

像所有此类性能优化一样,您应该只在进行大量分析后才能进行,以确保代码确实处于瓶颈中,并且可能考虑到微观性质,它正在紧密循环中运行.一般来说,Linux 开发人员都非常有经验,所以我想他们会这样做.他们并不太关心可移植性,因为他们只针对 gcc,而且他们对想要生成的程序集非常了解.

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天全站免登陆