Optimizing a branch for a known more-common path(为已知的更常见路径优化分支)
问题描述
请考虑以下代码:
void error_handling();
bool method_impl();
bool method()
{
const bool res = method_impl();
if (res == false) {
error_handling();
return false;
}
return true;
}
我知道 method_impl() 会返回 true 99.999%(是的,三位小数),但我的编译器不会.method() 在时间消耗方面是部分关键的.
I know method_impl() will return true 99.999% (yes, three decimal places) of the time, but my compiler doesn't. method() is partially critical in term of time-consumption.
- 我是否应该重写
method()(并降低可读性)以确保仅在method_impl()返回false时才可能发生跳转?如果是,如何? - 我应该让编译器为我做这些工作吗?
- 我应该让 CPU 的分支预测为我做这些工作吗?
- Should I rewrite
method()(and make it less readable) to ensure a jump may only occur whenmethod_impl()returnsfalse? If yes, how? - Should I let the compiler do the work for me?
- Should I let the branch prediction of my CPU do the work for me?
推荐答案
底层硬件已经执行了这种优化.第一次预测它会失败",但在它会命中正确的选项 en.wikipedia.org/wiki/Branch_predictor 之后.
The underlying hardware already performs this optimizations. It will "fail" to predict it the first times, but after it will hit the correct option en.wikipedia.org/wiki/Branch_predictor.
您可以尝试应用 GCC 扩展并检查使用它是否更快,但我认为您几乎看不出有和没有它的任何区别.总是应用分支预测,它不是你启用的东西
You can try applying the GCC extension and check if it is faster with it or not, but I think you will barely see any difference with it and without it. The branch prediction is applied always, it is not something you enable
这篇关于为已知的更常见路径优化分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为已知的更常见路径优化分支
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
