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?
std:sqrt
: en.cppreference.com/w/cpp/numeric/math/sqrt – Roilydouble
s, it's going to take a noticeably longer time to run than with justint
s. – Todddouble
(at least according to cppreference, or maybe I misunderstand it) which is equivalent to what would happen with::sqrt
? – Wellreadg++ test.cpp -o test
, no optimization flag. I've tested it with the compiler from mingw.org, both 32bit and 64bit. I'm not using C++11. – Clavius-S
for gcc)? – Conceited