2008/02/04

Fast, Fixed Point Square Root Computation ?

I did test your magic_sqrt but the time to execute sqrt() and magic_sqrt() are almost the same with my environment:

Linux, RHEL 4., x64, Xeon 3.2G x 2, 4MB memory gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-3), glib 2.3.4.

Here is the code:

[vuhung@ g++]$gcc -lm sqrt.c
[vuhung@ g++]$./a.out
sqrt time = 0.025689
magic sqrt time = 0.026223
[vuhung@ g++]$cat sqrt.c
#include
#include
#include
#include

float magic_sqrt (float number)
{
long i;
float f = 1.5, x = number/2, y = number;
i = * ( unsigned long * ) &y;
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * (f - x*y*y);
return number * y;

}

int main()
{
long i;

long NUM = 1000000;
float x;

double real, real_begin;
struct timeval tv;
gettimeofday (&tv, NULL);
real_begin = tv.tv_sec + (double) tv.tv_usec * 1e-6;

for(i = 0; i < NUM; i++)
x =sqrt(i + 0.01);

gettimeofday (&tv, NULL);
real = (tv.tv_sec + (double) tv.tv_usec * 1e-6);
printf (" sqrt time = %f\n", real - real_begin);


gettimeofday (&tv, NULL);
real_begin = tv.tv_sec + (double) tv.tv_usec * 1e-6;

for(i = 0; i < NUM; i++)
x = magic_sqrt(i + 0.01);
gettimeofday (&tv, NULL);
real = (tv.tv_sec + (double) tv.tv_usec * 1e-6);
printf ("magic sqrt time = %f\n", real - real_begin);

return 0;

}
http://www.qoheleth.uklinux.net/blog/?p=139
http://themanaworld.org/tmwservdox/mathutils_8cpp-source.html

0 件のコメント: