加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么sqrt变得更快没有-O2在我的电脑上?

发布时间:2020-12-16 07:52:35 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: #include cstdio#include cmathconst int COUNT = 1000000000;int main(){ double sum = 0; for (int i = 1; i = COUNT; ++i) { sum += sqrt(i); } printf("%fn",sum); return 0;} 没有-O2,它在我的电脑上运行只有2.9s,而运行6.4s与-O2.
请考虑以下代码:
#include <cstdio>
#include <cmath>

const int COUNT = 1000000000;

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

没有-O2,它在我的电脑上运行只有2.9s,而运行6.4s与-O2.

我的电脑是Fedora 23,g 5.3.1.

我在Ubuntu 14.04(与g 4.8)一样尝试过同样的事情,它没有问题(全部6.4s).

解决方法

Naive版本使用调用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 compile选项.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读