【问题标题】:fast inversion algorithm slower than math.h 1/sqrt function比 math.h 1/sqrt 函数慢的快速反演算法
【发布时间】:2014-03-14 15:46:02
【问题描述】:

我只是想了解为什么快速反演算法比 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;
    }

【问题讨论】:

  • 您是否尝试过查看为这两个版本生成的汇编代码?浮点库通常经过大量优化,并使用硬件支持。

标签: c algorithm sqrt quake


【解决方案1】:

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

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

【讨论】:

  • 在 unix/linux 上,您可以通过执行 gcc -S your_source_file.c 编译为仅汇编,或者使用 objdump -d your_executable 反汇编最终的可执行文件。然后,您可以检查组装清单,以确切了解正在使用的硬件指令。
【解决方案2】:

this 问题相反,sqrt 或逆sqrt 可能已在 CPU 级别进行了优化。
进一步:您是否对具有最高优化级别的代码进行了基准测试?

奇数魔术常数利用 32 位 IEEE 浮点的表示,为牛顿迭代提取了良好的初始近似值。

【讨论】:

  • 在 gcc 中,使用例如-march=native -ffast-math -O6 -S
【解决方案3】:

如果您真的想演示“慢”与“快”,您需要真正了解这两种算法的作用,因为没有特殊理由认为 sqrt() 很慢。编写自己的 slow_sqrt 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多