簡體   English   中英

快速反演算法比math.h 1 / sqrt函數慢

[英]fast inversion algorithm slower than math.h 1/sqrt function

我只想了解為什么快速反演算法比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()硬件,這使其比軟件方法要快。 如果沒有更多有關您的系統的詳細信息,或者可能缺少一些概要分析和反匯編數據,就很難說出來。

看到這個答案大約為x86的循環次數細節fsqrt指令,例如。

問題相反,sqlt或逆sqrt可能已在CPU級別上進行了優化。
此外:您是否以最高級別的優化為基准測試了代碼?

奇數魔術常數利用32位IEEE浮點的表示形式,為牛頓迭代提取了良好的初始近似值。

如果您真的想演示“慢速”與“快速”,您實際上需要知道兩種算法的作用,因為沒有特殊理由認為sqrt()很慢。 編寫自己的slow_sqrt函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM