c - 快速反演算法比 math.h 1/sqrt 函数慢

标签 c algorithm sqrt quake

我只是想了解为什么快速求逆算法比 math.h sqrt 函数慢。这是我的代码示例

代码尝试演示比较慢速反转和快速反转。在调试时,我看到慢速反转需要 1 秒,快速反转需要 4 秒。问题出在哪里?

    #include<stdio.h>
    #include<time.h>
    #include<math.h>
    #include"inverse.h"

    #define SIZE 256

    int main()
    {
       char buffer[SIZE];
       time_t curtime;
       time_t curtime2;
       struct tm *loctime;
       int i = 0;
       float x = 0;

       curtime = time(NULL);
       loctime = localtime (&curtime);
       fputs (asctime (loctime), stdout);

       while(i < 100000000)
       {
          i++;
          //x = 1/sqrt(465464.015465);
          x = inverse_square_root(465464.015465);
       }

       curtime = time(NULL);
       loctime = localtime (&curtime);
       fputs (asctime (loctime), stdout);

       getchar();
       return 0;
    }

    float inverse_square_root(float number)
    {
       long i;
       float x2, y;
       const float threehalfs = 1.5F;

       x2 = number * 0.5F;
       y  = number;
       i  = * ( long * ) &y;             // evil floating point bit level hacking
       i  = 0x5f3759df - ( i >> 1 );     // what the heck?
       y  = * ( float * ) &i;
       y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
    // y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed
       return y;
    }

最佳答案

“问题”可能是您现在拥有实现 sqrt() 的硬件,使其比软件方法更快。如果没有更多关于您的系统的详细信息以及一些分析和反汇编数据,很难判断。

See this answer例如,了解有关 x86 fsqrt 指令的周期数的详细信息。

关于c - 快速反演算法比 math.h 1/sqrt 函数慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409727/

相关文章:

c - 如何检查一个数字是否更接近某个特定数字?

c - 二进制搜索算法的每次迭代是否可以只进行一次比较?

perl - 如何设置Raku的sqrt的精确度?

.net - 如何捕获 'n. def' 异常(例如 : Sqrt of negative double number)

c - 只是想确保我理解外部变量是什么

使用Makefile : how to do it right for several programs?进行编译

java - Java中的快速双值优先级队列实现

algorithm - 如何以高效简单的方式解决 5 * 5 立方体

algorithm - 如何查找出现次数大于2的字符串中的所有字符

c++ - long double sqrt() 的精度