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!