为已知的更常见路径优化分支

Optimizing a branch for a known more-common path(为已知的更常见路径优化分支)
本文介绍了为已知的更常见路径优化分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

请考虑以下代码:

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.

  1. 我是否应该重写method()(并降低可读性)以确保仅在method_impl() 返回false 时才可能发生跳转?如果是,如何?
  2. 我应该让编译器为我做这些工作吗?
  3. 我应该让 CPU 的分支预测为我做这些工作吗?
  1. Should I rewrite method() (and make it less readable) to ensure a jump may only occur when method_impl() returns false? If yes, how?
  2. Should I let the compiler do the work for me?
  3. 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

这篇关于为已知的更常见路径优化分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)