I'm trying to optimize a simple Euclidian distance function in C. It's for a DLL, and calculates distances from one point to many. I have:
Version 1:
int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distances)
{
double dx,dy = 0;
for (int i = 0;i<nb;i++)
{
dx = x2[i] - x1;
dy = y2[i] - y1;
distances[i]=(int)sqrt((dx*dx)+(dy*dy));
}
return nb;
}
Version 2:
int CalcDistance (int y1, int x1, int *y2, int *x2, int nb , int *distance)
{
int dx,dy =0;
for (int i = 0;i<nb;i++)
{
dx = x2[i] - x1;
dy = y2[i] - y1;
distances[i]=(int)sqrt((double)(dx*dx)+(dy*dy));
}
return nb;
}
Essentially, I don't need extra high precision, so that's why I'm cutting down to ints, not doubles. For my specific use case, the final distance will not be larger than what an int (Int32) can hold.
I was taken aback by how slow version 2 was. I figured that in Version 1 calculating dx
and dy
would implicitly cast to double
twice, whereas in version 2 I'm just explicitly casting once. What's happening? And ultimately, what could be even faster?
(And I tried _hypot
, which was oddly the slowest of all...)