fork download
  1. #include <iostream>
  2. #include <chrono>
  3. #include <cstdint>
  4. #include <cmath>
  5. #include <ratio>
  6. using namespace std;
  7.  
  8. float InvSqrt(float x){
  9. float xhalf = 0.5f * x;
  10. int i = *(int*)&x; // store floating-point bits in integer
  11. i = 0x5f3759df - (i >> 1); // initial guess for Newton's method
  12. x = *(float*)&i; // convert new bits into float
  13. x = x*(1.5f - xhalf*x*x); // One round of Newton's method
  14. return x;
  15. }
  16.  
  17. int main() {
  18. const int32_t SampleSize = 1000000;
  19. int64_t Resolution = std::chrono::high_resolution_clock::period::den;
  20. std::cout << "Resolution: " << Resolution << std::endl;
  21. float Sum = 0.0f;
  22. auto Begin = std::chrono::high_resolution_clock::now();
  23. for(int32_t i=1;i<SampleSize;i++){
  24. Sum+=1.0f/sqrtf((float)i);
  25. }
  26. auto End = std::chrono::high_resolution_clock::now();
  27. std::cout << "Time Taken for 1/sqrt(i): " << (std::chrono::duration_cast<std::chrono::duration<double>>(End-Begin)).count() << " seconds. Total Sum: " << Sum << std::endl;
  28. Sum = 0.0f;
  29. Begin = std::chrono::high_resolution_clock::now();
  30. for(int32_t i=1;i<SampleSize;i++){
  31. Sum+=InvSqrt((float)i);
  32. }
  33. End = std::chrono::high_resolution_clock::now();
  34. std::cout << "Time Taken for InvSqrt(i): " << (std::chrono::duration_cast<std::chrono::duration<double>>(End-Begin)).count() << " seconds. Total Sum: " << Sum << std::endl;
  35.  
  36. // your code goes here
  37. return 0;
  38. }
Success #stdin #stdout 0.03s 3096KB
stdin
Standard input is empty
stdout
Resolution: 1000000000
Time Taken for 1/sqrt(i): 0.0247454 seconds. Total Sum: 1998.54
Time Taken for InvSqrt(i): 0.00630476 seconds. Total Sum: 1996.65