我有一个问题:对于计算double的简单整数幂,pow()函数比简单乘法慢吗?例如2.71828^4
,比使用for循环的简单乘法慢pow(2.71828, double(4))
?
我试图比较两种方法的持续时间,但持续时间不稳定,有时pow()
获胜,有时简单的乘法获胜。任何人都可以给我一个确认答案吗?
我的代码如下:
#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;
}
非常感谢!
答案 0 :(得分:0)
是的,pow比乘法慢,乘法比加法慢。权衡是,对于像pow(x,2)这样的简单幂,使用x * x代替