为什么sqrt在我的计算机上没有-O2 in g ++的情况下变得更快?

deb*_*g18 10 c++ performance g++ sqrt

请考虑以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

没有-O2,它在我的计算机上只运行2.9秒,而运行6.4秒-O2.

我的电脑是Fedora 23,带有g ++ 5.3.1.

我在Ubuntu 14.04(使用g ++ 4.8)上尝试了相同的东西,它没有问题(所有6.4s).

gud*_*dok 3

Naive 版本使用对 glibcsqrt函数的调用。

优化版本使用SSEsqrtsd指令。但指令完成后,它会检查结果值是否不是 NaN。如果结果值为 NaN,则它调用 glibcsqrt函数来设置正确的错误标志(请参阅手册页math_error(7))。有关详细说明,请参阅为什么编译器在编译的汇编代码中生成额外的 sqrt 。

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