title: Benchmarking math.h square root and Quake square root
body: <p>Okay so I was board and wondered how fast math.h square root was in comparison to the one with the magic number in it (made famous by Quake but made by SGI).</p>
  
  <p>But this has ended up in a world of hurt for me.</p>
  
  <p>I first tried this on the Mac where the math.h would win hands down every time then on Windows where the magic number always won, but I think this is all down to my own noobness.</p>
  
  <ol>
  <li><p>Compiling on the Mac with "g++ -o sq_root sq_root_test.cpp" when the program ran it takes about 15 seconds to complete. But compiling in VS2005 on release takes a split second. (in fact I had to compile in debug just to get it to show some numbers)</p></li>
  <li><p>My poor man's benchmarking? is this really stupid? cos I get 0.01 for math.h and 0 for the Magic number. (it cant be that fast can it?)</p></li>
  </ol>
  
  <p>I don't know if this matters but the Mac is Intel and the PC is AMD. Is the Mac using hardware for math.h sqroot?</p>
  
  <p>I got the fast square root algorithm from <a href="http://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="nofollow">http://en.wikipedia.org/wiki/Fast_inverse_square_root</a></p>
  
  <pre><code>//sq_root_test.cpp
  
  #include &lt;iostream&gt;
  #include &lt;math.h&gt;
  #include &lt;ctime&gt;
  
  
  float invSqrt(float x)
  {
      union {
          float f;
          int i;
      } tmp;
      tmp.f = x;
      tmp.i = 0x5f3759df - (tmp.i &gt;&gt; 1);
      float y = tmp.f;
      return y * (1.5f - 0.5f * x * y * y);
  }
  
  int main() {
      std::clock_t start;// = std::clock();
      std::clock_t end;
      float rootMe;
  
      int iterations = 999999999;
  
      // ---
  
      rootMe = 2.0f;
      start = std::clock();
  
      std::cout &lt;&lt; "Math.h SqRoot: ";
  
      for (int m = 0; m &lt; iterations; m++) {
          (float)(1.0/sqrt(rootMe));
          rootMe++;
      }
  
      end = std::clock();
  
      std::cout &lt;&lt; (difftime(end, start)) &lt;&lt; std::endl;
  
      // ---
  
      std::cout &lt;&lt; "Quake SqRoot: ";
  
      rootMe = 2.0f;
      start = std::clock();
  
      for (int q = 0; q &lt; iterations; q++) {
          invSqrt(rootMe);
          rootMe++;
      }
  
      end = std::clock();
  
      std::cout &lt;&lt; (difftime(end, start)) &lt;&lt; std::endl;   
  }
  </code></pre>