我们可以信任编译器优化多少
How much we can trust compiler optimization?
我写了以下代码,以计算两个圆的相交点。代码很简单且足够快。并不是说我需要更多的优化,而是我可以考虑更积极地优化此代码。例如,计算两次h/d
和1.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()
的知识。
相关文章:
- 空基优化子对象的地址
- 复制列表初始化的隐式转换的等级是多少
- while循环中while循环的时间复杂度是多少
- 关闭||运算符优化
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何检查一个c++字符串中有多少相同的字符/数字
- C++有多少类型的循环
- 返回值优化:显式移动还是隐式
- 人脸跟踪arduino代码的优化
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 纯函数,为什么没有优化
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 如何以优化的方式同时迭代两个间距不相等的数组
- 在条件变量中触发错误信号的频率是多少
- 函数的时间复杂度是多少?
- 在没有返回值优化的情况下将两个对象加在一起时,将创建多少个临时对象
- 我们可以信任编译器优化多少
- 假设没有编译器优化,则将创建多少次此对象
- 优化编译器如何决定何时展开循环以及展开多少循环