中心からの距離を測って閾値などと比べるのにsqrt()を使っている例を見ました。比較であれば2乗したほうが早そうだなと思い、特に調べず速度測定してみました。
#include <iostream>
#include <windows.h>
int main(void) {
double tx = 5;
double yy;
int till = 500000000;
double start = GetTickCount();
for (int i = 0; i < till; i++) {
yy = std::sqrt(tx);
}
double end = GetTickCount();
double result = end - start;
std::cout << "sqrt:" << result << std::endl;
start = GetTickCount();
for (int i = 0; i < till; i++) {
yy = tx*tx;
}
end = GetTickCount();
result = end - start;
std::cout << "square:" << result << std::endl;
return 0;
}
結果
sqrt:3125
square:1109
tillをどう変えても明らかに二乗が早かった(当たり前)