상세 컨텐츠

본문 제목

Pow (x, 0.5) vs Sqrt (x)

카테고리 없음

by DeaKyungLee 2022. 12. 17. 14:35

본문

Question:

Who is the better performance?


 

실험 환경 : VS 2017, ISO C++17 표준(/std:c++17)

 

실험코드

더보기

 

#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <time.h>
 
using namespace std;
 
class ClockTime
{
private:
    clock_t start, end;
    double time;
public:
    ClockTime() { Init(); }
    void Start()
    {
        start = clock();
    }
 
    double End(bool bPrintTime = false)
    {
        end = clock();
        time = (double)(end - start) / CLOCKS_PER_SEC;
 
        if (bPrintTime)
            cout << time << "\n";
 
        return time;
    }
 
    void Init()
    {
        start = end = time = 0;
    }
};
 
 
int main()
{
    const int runTime = 100;
    const int eachRunTime = 1000000000;     // 100,000,000 = 1억
 
    std::ofstream ofilePow("powTime.txt"), ofileSqrt("sqrtTime.txt");
    for (int epoch = 0; epoch < runTime; epoch++)
    {
        ClockTime myClock;
        myClock.Start();
 
        for (int i = 0; i < eachRunTime; i++)
            pow(double(100), 0.5);
 
        //cout << "pow: ";
        string powTime = to_string( myClock.End());
        ofilePow << powTime << "\n";;
 
        //////////////////////////////////////////////////////
 
        myClock.Init();
        myClock.Start();
 
        for (int i = 0; i < eachRunTime; i++)
            sqrt(double(100));
 
        //cout << "sqrt: ";
        string sqrtTime = to_string(myClock.End());
        ofileSqrt << sqrtTime << "\n";
    }
 
     
    ofilePow.close();
    ofileSqrt.close();
 
 
    return 0;
}
  • pow(double(100), 0.5); or pow(double(i), 0.5)
  • sqrt(double(100)); or sqrt(double(i));

-> 각 코드를 1억번씩, 100번 수행

 

실험 결과

참고 답변:

https://stackoverflow.com/questions/17417490/difference-between-sqrtx-and-powx-0-5

 

Difference between sqrt(x) and pow(x,0.5)

I was wondering why there is sqrt() function in C/c++ as we can achieve the same using pow(x,0.5); how is sqrt(x) different for pow(x,0.5) . Is there a specific reason of having sqrt function?

stackoverflow.com

https://stackoverflow.com/questions/11810686/is-fast-implementation-of-powx-0-5f-faster-than-fast-sqrtx

 

Is fast implementation of pow(x, 0.5f) faster than fast sqrt(x)?

I'm wondering if fast implementation of pow(), for example this one, is a faster way to get square root of an integer than fast sqrt(x). We know that sqrt(x) = pow(x, 0.5f) I cannot test speed my...

stackoverflow.com

 

 

결론

  • 순수하게 제곱근을 구하는 용도라면 sqrt가 더 빠르고 정확하다.
    -> 더 효율적인 어셈블리 코드를 사용
  • 가독성 또한 sqrt 활용이 더 좋다.
    -> 더 명확한 의도 전달이 가능하다.

댓글 영역