为什么全球范围内的sqrt比MinGW中的std :: sqrt慢得多? [英] Why sqrt in global scope is much slower than std::sqrt in MinGW?

查看:176
本文介绍了为什么全球范围内的sqrt比MinGW中的std :: sqrt慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  #include  #include< cstdio> 

const int COUNT = 100000000;

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

它在我的电脑上运行5.5秒。但是,如果我将 sqrt 更改为 std :: sqrt ,它将只运行0.7s。



我知道如果使用 sqrt ,我使用C库中的函数,如果我使用 std :: sqrt ,我使用< cmath> 中的一个。



< cmath> 没有为 int 定义一个,如果我改变 i 转换为 double ,它们将以相同的速度运行。所以编译器没有针对 int 进行优化。这似乎只发生在Windows中 sqrt

所以为什么 std :: sqrt sqrt 快得多,但不是其他函数?为什么在Linux中它们不是?

解决方案

这是 -fdump- tree - * switch可以给出一些有关正在发生的事情的信息:

  g ++ -fdump-tree -optimized example1.cc 

,您将获得 example1.cc.165t。优化文件。

 < bb 3> ;: 
_5 =(double)i_2;
_6 = sqrt(_5);
sum_7 = sum_1 + _6;
i_8 = i_2 + 1;

编译器(gcc v4.8.3)用 double s。



替换 sqrt std :: sqrt 您得到的是:

 < bb 3>:
_5 = std :: SQRT< INT> (I_2);
sum_6 = sum_1 + _5;
i_7 = i_2 + 1;

现在它对整数使用不同的sqrt重载( i_2 int sum_6 double )。

正如Mike Seymour在

无论如何,在Linux下,两种实现之间并没有明显的性能差异。

在Windows(MinGW)下,这是不同的,因为 sqrt(double)调用 msvcrt


Consider the following code:

#include <cmath>
#include <cstdio>

const int COUNT = 100000000;

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

It runs 5.5s on my computer. However, if I change sqrt into std::sqrt, It will run only 0.7s.

I know that if I use sqrt, I'm using the function from C library, and if I use std::sqrt, I'm using the one in <cmath>.

But <cmath> doesn't define one for int, and if I change the type of i into double, they will run for equal speed. So the compiler isn't optimizing for int. This seems to only happen to sqrt in Windows.

So why is std::sqrt much faster than sqrt, but not other functions? And why in Linux they are not?

解决方案

This is the typical situation in which the -fdump-tree-* switch can give some insight into what is going on:

g++ -fdump-tree-optimized example1.cc

and you get the example1.cc.165t.optimized file. Somewhere inside:

<bb 3>:
_5 = (double) i_2;
_6 = sqrt (_5);
sum_7 = sum_1 + _6;
i_8 = i_2 + 1;

The compiler (gcc v4.8.3) is doing the math with doubles.

Replacing sqrt with std::sqrt what you get is:

<bb 3>:
_5 = std::sqrt<int> (i_2);
sum_6 = sum_1 + _5;
i_7 = i_2 + 1;

Now it uses a different sqrt overload for integers (i_2 is int and sum_6 is double).

As Mike Seymour says in a comment, GCC uses the new overload whether or not you specify C++11.

Anyway under Linux there isn't a sensible performance difference between the two implementations.

Under Windows (MinGW) this is different since sqrt(double) calls into msvcrt.

这篇关于为什么全球范围内的sqrt比MinGW中的std :: sqrt慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆