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

查看:86
本文介绍了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 */
}

我已经找到了它们的定义:

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.

就像所有这样的性能优化一样,您应该只在进行广泛的性能分析后才能执行此操作,以确保代码确实处于瓶颈,并且可能考虑到微观性质,因此代码正在紧密循环中运行.通常,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天全站免登陆