Is there any advantage to using pow(x,2) instead of x*x, with x double?

前端 未结 8 902
清酒与你
清酒与你 2020-12-03 04:18

is there any advantage to using this code

double x;
double square = pow(x,2);

instead of this?

double x;
double square = x*         


        
8条回答
  •  青春惊慌失措
    2020-12-03 04:49

    In C++11 there is one case where there is an advantage to using x * x over std::pow(x,2) and that case is where you need to use it in a constexpr:

    constexpr double  mySqr( double x )
    {
          return x * x ;
    }
    

    As we can see std::pow is not marked constexpr and so it is unusable in a constexpr function.

    Otherwise from a performance perspective putting the following code into godbolt shows these functions:

    #include 
    
    double  mySqr( double x )
    {
          return x * x ;
    }
    
    double  mySqr2( double x )
    {
          return std::pow( x, 2.0 );
    }
    

    generate identical assembly:

    mySqr(double):
        mulsd   %xmm0, %xmm0    # x, D.4289
        ret
    mySqr2(double):
        mulsd   %xmm0, %xmm0    # x, D.4292
        ret
    

    and we should expect similar results from any modern compiler.

    Worth noting that currently gcc considers pow a constexpr, also covered here but this is a non-conforming extension and should not be relied on and will probably change in later releases of gcc.

提交回复
热议问题