为什么全球范围内的sqrt比MinGW中的std :: sqrt慢得多? [英] Why sqrt in global scope is much slower than std::sqrt in MinGW?
问题描述
请考虑以下代码:
#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>
中的一个。
但 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)下,这是不同的,因为 Consider the following code: It runs 5.5s on my computer. However, if I change I know that if I use But So why is This is the typical situation in which the and you get the The compiler (gcc v4.8.3) is doing the math with Replacing Now it uses a different sqrt overload for integers ( 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比MinGW中的std :: sqrt慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
sqrt(double)
调用 msvcrt
。
#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;
}
sqrt
into std::sqrt
, It will run only 0.7s.sqrt
, I'm using the function from C library, and if I use std::sqrt
, I'm using the one in <cmath>
.<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.std::sqrt
much faster than sqrt
, but not other functions? And why in Linux they are not?-fdump-tree-*
switch can give some insight into what is going on:g++ -fdump-tree-optimized example1.cc
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;
double
s.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;
i_2
is int
and sum_6
is double
).sqrt(double)
calls into msvcrt
.