gpt4 book ai didi

c++ - 为什么在我的计算机上没有 g++ 中的 -O2 时 sqrt 会变得更快?

转载 作者:可可西里 更新时间:2023-11-01 16:18:53 26 4
gpt4 key购买 nike

考虑以下代码:

#include <cstdio>
#include <cmath>

const int COUNT = 1000000000;

int main()
{
double sum = 0;
for (int i = 1; i <= COUNT; ++i) {
sum += sqrt(i);
}
printf("%f\n", sum);
return 0;
}

没有 -O2,它在我的电脑上只运行 2.9s,而使用 -O2 运行 6.4s。

我的电脑是 Fedora 23,g++ 5.3.1。

我在 Ubuntu 14.04(使用 g++ 4.8)上尝试过同样的事情,它没有问题(所有 6.4s)。

最佳答案

原始版本使用调用 glibc sqrt 函数。

优化版使用 SSE sqrtsd 指令。但是在指令完成后,它会检查结果值是否不是 NaN。如果结果值为 NaN,则它调用 glibc sqrt 函数来设置正确的错误标志(参见 math_error(7) 的手册页)。参见 Why does compiler generate additional sqrts in the compiled assembly code详细解释。

为什么 gcc 认为这样更快?没人知道。如果您确定您的数字不会生成 NaN,请使用 -fno-math-errno 编译选项。

关于c++ - 为什么在我的计算机上没有 g++ 中的 -O2 时 sqrt 会变得更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com