gcc可能不太可能使用宏 [英] gcc likely unlikely macro usage

查看:138
本文介绍了gcc可能不太可能使用宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段关键的代码,大致有以下逻辑:

I am writing a critical piece of code with roughly the following logic

if(expression is true){
   //do something with extremely low latency before the nuke blows up. This branch is entered rarely, but it is the most important case
}else{
   //do unimportant thing that doesnt really matter
}

我正在考虑在表达式中使用likely()宏,所以当它碰到重要的分支时,我会得到最小的延迟。我的问题是,这个用法与宏名称暗示相反,因为我选择'不太可能'的分支来预取。在性能方面是否存在明显的缺点?

I am thinking to use likely() macro around the expression, so when it hits the important branch, I get minimum latency. My question is that the usage is really opposite of the macro name suggest because I am picking the 'unlikely' branch to be pre-fetch. Is there a clear downside of doing this in terms of performance?

推荐答案

是的。您正在欺骗编译器,通过将不太可能但必须快速的分支标记为可能的分支,希望编译器能加快速度。

Yes. You are tricking the compiler by tagging the unlikely-but-must-be-fast branch as if it were the likely branch, in hopes that the compiler will make it faster.

这样做有一个明显的缺点 - 如果你不写一篇好的评论来解释你在做什么以及为什么,一些维护者(可能是你自己)在六个月内几乎可以保证说:嘿,看起来像他把错误的分支放在错误的分支上并修复它。

There is a clear downside in doing that—if you don't write a good comment that explains what you're doing and why, some maintainer (possibly you yourself) in six months is almost guaranteed to say, "Hey, looks like he put the likely on the wrong branch" and "fix" it.

还有一种不太可能的但仍然可能的缺点,就是某些版本的编译器现在或将来的使用会做出与预期的可能宏不同的事情,而这些不同的事情不会成为你想让编译器做的事情,而且你最终会得到代码,每次都会循环,花费10万美元投机取得通过反应堆关闭90%的方式之前撤消它。

There is also a much less likely but still possible downside, that some version of some compiler that you use now or in the future will do different things than you're expecting with the likely macro, and those different things will not be what you wanted to trick the compiler into doing, and you'll end up with code that, every time through the loop, spends $100K speculatively getting 90% of the way through reactor shutdown before undoing it.

这篇关于gcc可能不太可能使用宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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