4

I have got one question: for calculating simple integer powers of a double, is pow() function slower than simple multiplication? such as for 2.71828^4, is pow(2.71828, double(4)) slower than the simple multiplication using for loop?

I have tried to compare the durations for both approaches, but the durations are not stable, sometimes pow() wins and sometimes simple multiplication wins. Can anyone give me an confirmatory answer?

my code is as followed:

#include <iostream>
#include <cmath>
#include <ctime>

using namespace std;

double myFunction(double a) {
    double c = 1;
    for (int i = 1; i <= 4; i++)
        c *= a;
    return c;
}

int main() {
    // Calculate the time used by pow function
    clock_t start = clock();
    for (double i = 0; i < 1000000; i = i + 0.001)
        pow(i, 4);
    clock_t durationP = double(clock() - start);
    cout << "the duration for pow function is:   " << durationP << "s" << endl;

    // Calculate the time used by simple multiplication
    start = clock();
    for (double i = 0; i < 1000000; i = i + 0.001)
        myFunction(i);
    double durationS = double(clock() - start);
    cout << "the duration for simple multiplication is:" << durationS << "s"
         << endl;
}

thanks a lot!

NetVipeC
  • 4,402
  • 1
  • 17
  • 19
  • It's written there that `pow()` is slower, as the base is casted to double, and `double` arithmetic functions cost more CPU operations. I'd suggest not to use `pow()` and not to use multiplication. Simply, for readability, create your own `powInt(int,int)` function, that will multiply the integers – SomethingSomething Sep 08 '14 at 13:36

1 Answers1

1

Yes, pow is slower than multiplication, multiplication is slower than addition. Tradeoff is, for simple power like pow(x, 2), use x*x instead

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
  • hi! thanks for reply! and another question is why in my program the durations for both approaches are not stable time? Sometimes, pow() takes longer and sometimes simple multiplication takes longer.Thanks – Jessica.Jin Sep 08 '14 at 13:28
  • 1
    Multiplication has not been slower than addition on hardware in the last 15 years or so. – jupp0r Sep 08 '14 at 13:30
  • Ok, timing depends on many things, whether CPU was doing this task only or some other task etc – Dr. Debasish Jana Sep 08 '14 at 13:30
  • Multiplication is slower than addition? We're talking floating point here, the two often (though not always) have the same throughput and latency even on relatively simplistic designs like the shader cores in GPUs. *Integer* multiplication often at least has higher latency though, even on modern high-end CPUs. –  Sep 08 '14 at 13:32
  • @jupp0r float operations are in the order of a cycle slower than int, though the bandwidth in doubles is half the same in floats and ints, keep that in mind – BeyelerStudios Sep 08 '14 at 15:42