likely() 和unlikely() 编译器提示的学习示例
我如何向学生演示likely
和unlikely
编译器提示(__builtin_expect
)的可用性?
你能写一个示例代码吗,有这些提示的代码与没有提示的代码相比会快几倍。
How can I demonstrate for students the usability of likely
and unlikely
compiler hints (__builtin_expect
)?
Can you write an sample code, which will be several times faster with these hints comparing the code without hints.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我使用的斐波那契数列的一种非常低效的实现:
为了演示,使用 GCC:
少了几百毫秒。这种增益归功于程序员辅助的分支预测。
但现在,程序员真正应该做的事情是:
通过编译器辅助的运行时分析,我们成功地将时间从原来的 34.290 秒减少到 17.760 秒。比程序员辅助的分支预测好得多!
Here is the one I use, a really inefficient implementation of the Fibonacci numbers:
To demonstrate, using GCC:
A few hundred milliseconds less. This gain is due to the programmer-aided branch prediction.
But now, for what the programmer should really be doing instead:
With compiler-aided runtime profiling, we managed to reduce from the original 34.290s to 17.760s. Much better than with programmer-aided branch prediction!
从这个博客 帖子。我认为“可能”和“不太可能”大多已经过时了。非常便宜的 CPU(示例中的 ARM Cortex A20)具有分支预测器,并且无论是否进行跳转,都不会受到惩罚。当您引入可能/不可能时,结果将相同或更差(因为编译器生成了更多指令)。
From this blog post. I think likely and unlikely are mostly obsolete. Very cheap CPUs (ARM Cortex A20 in the example) have branch predictors and there is no penalty regardless of jump is taken / jump is not taken. When you introduce likely/unlikely the results will be either the same or worse (because compiler has generated more instructions).