::pow(T, n) vs std::pow(T, n) for non-constant n

Paolo Carlini pcarlini@suse.de
Sun Mar 14 12:48:00 GMT 2004


Richard Guenther wrote:

> Hmm, I can't get it to recognize the constant-ness.  You should look 
> at the generated assembler.  Probably the loop is just optimized away 
> because you don't use the result of ::pow() and ::pow() is probably 
> const or pure while std::pow() is not (it should probably be).

Yes, you are right, my previous results were misleading.
For this (-O2 -ffast-math)

#include <cmath>
#include <iostream>

double
f()
{
  double ris = 0.0;

  for (int i = 0; i < 100000000; ++i)
    {
      double a = M_PI * i;
      int n = i % 10;
      ris += std::pow(a, n);
      //ris += ::pow(a, n);
    }

  return ris;
}

int main()
{
  std::cout << f() << '\n';
}

::pow
-----
22.470u 0.010s 0:22.57 99.6%    0+0k 0+0io 215pf+0w

std::pow
--------
2.130u 0.010s 0:02.15 99.5%     0+0k 0+0io 210pf+0w

So, you see that when the const-ness cannot be established and library
calls are involved, the binary-algorithm *is* faster.

> It should be more accurate than v3 in any case.  The only thing is, 
> std::pow() defaults to something like -ffast-math, while 
> __builtin_pow() does not.  This can be surprising to users.

Yes, ::pow is more accurate in any case, but not always faster (faster
only when const arguments are involved)

Paolo.



More information about the Libstdc++ mailing list