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?