Tuesday, May 16, 2017

C++: Euclidean distance variations


So how about this new std::hypot?


 float dx = x1 - x2;
 float dy = y1 - y2;
 return std::hypot(dx, dy);


Time: 12139783 ticks

How about the old one std::sqrt?


 float dx = x1 - x2;
 float dy = y1 - y2;
 return std::sqrt(dx*dx + dy*dy);


Time: 7026125 ticks (1.7 times faster)

Oh, the std::hypot performs an overflow check, so if you don't care about that just use std::sqrt

And of course the very old std:: nothing


 float dx = x1 - x2;
 float dy = y1 - y2;
 return dx*dx + dy*dy;


Time: 5667812 ticks (2.1 and 1.2 times faster)

Wait, can I just do


 return (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);


and let the optimizer fix it. Lets check

Time: 5592648 ticks (seems the same)


Source


done_