我们可以信任编译器优化多少

How much we can trust compiler optimization?

本文关键字:优化 多少 编译器 信任 我们      更新时间:2023-10-16

我写了以下代码,以计算两个圆的相交点。代码很简单且足够快。并不是说我需要更多的优化,而是我可以考虑更积极地优化此代码。例如,计算两次h/d1.0/d(让我们忘记编译器优化)。

const std::array<point,2> intersect(const circle& a, 
                                         const circle& b) {
    std::array<point,2> intersect_points;
    const float d2 = squared_distance(a.center, b.center);
    const float d = std::sqrt(d2);
    const float r12 = std::pow(a.radious, 2);
    const float r22 = std::pow(b.radious, 2);
    const float l = (r12 - r22 + d2) / (2*d);
    const float h = std::sqrt(r12 - std::pow(l,2));
    const float termx1 = (1.0/d) * (b.center.x - a.center.x) + a.center.x;
    const float termx2 = (h/d)*(b.center.y - a.center.y);
    const float termy1 = (1.0/d) * (b.center.y - a.center.y) + a.center.y;
    const float termy2 = (h/d)*(b.center.x - a.center.x);
    intersect_points[0].x = termx1 + termx2;
    intersect_points[0].y = termy1 - termy2;
    intersect_points[1].x = termx1 - termx2;
    intersect_points[1].y = termy1 + termy2;
    return intersect_points;
}

我的问题是,我们可以信任C 编译器(这里的G )以了解代码并优化最终二进制文件?G 可以避免两次1.0/d吗?更确切地说,我想知道这条线在哪里。当我们应该将微调放到编译器时,什么时候进行优化?

流行的编译器如今非常出色。优化器很可能会检测到1.0/d等通用表达式,因此不在乎这一点。优化器将std:pow( x, 2 )替换为x * x的可能性要小得多。这取决于您使用的确切函数,所使用的编译器版本和优化命令行开关。因此,在这种情况下,最好写x * x。很难说优化器可以走多远,当您作为人类必须接管时,这取决于优化器的"智能"。但是,根据经验,编译器可以优化它可以从代码行中扣除的内容。例子:编译器会知道,这个术语始终是错误的: 1 == 2但是它不知道这也总是错误的: 1 == nextPrimeAfter(1),因为它必须了解函数 nextPrimeAfter()的知识。