/* Type your code here, or load an example. */
int square(int num) {
return num * num;
}
#include <stdio.h>
#include <time.h>
/* Normal Q_rsqrt code */
float Q_rsqrt(float number)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(long *)&y;
i = 0x5f3759df - (i >> 1);
y = *(float *)&i;
y = y * (threehalfs - (x2 * y * y));
return y;
}
/* PR code */
float Q_rsqrt1( float number )
{
long i;
float x2, y;
x2 = number * 0.5F;
i = 0x5f3759df - ( * ( long * ) &number >> 1 );
y = * ( float * ) &i;
y = y * ( 1.5F - ( x2 * y * y ) );
return y;
}
/* My union version */
float Q_rsqrt2(float number)
{
return ({
union { float f; unsigned i; } u = { number };
u.i = 0x5f3759df - (u.i >> 1);
u.f * (1.5f - 0.5f * number * u.f * u.f);
});
}
int main()
{
const int iterations = 10000000;
volatile float res;
clock_t start, end;
int i;
res = Q_rsqrt(10.0f);
res = Q_rsqrt1(10.0f);
res = Q_rsqrt2(10.0f);
start = clock();
for (i = 0; i < iterations; i++) {
res = Q_rsqrt((float)i + 1.0f);
}
end = clock();
printf("Q_rsqrt time: %f s\n", (double)(end - start) / CLOCKS_PER_SEC);
start = clock();
for (i = 0; i < iterations; i++) {
res = Q_rsqrt1((float)i + 1.0f);
}
end = clock();
printf("Q_rsqrtO time: %f s\n", (double)(end - start) / CLOCKS_PER_SEC);
start = clock();
for (i = 0; i < iterations; i++) {
res = Q_rsqrt2((float)i + 1.0f);
}
end = clock();
printf("Q_rsqrt1 time: %f s\n", (double)(end - start) / CLOCKS_PER_SEC);
/* Prevent compiler from optimizing function calls out */
printf("Result check: %f\n", res);
return 0;
}