昨天在PKU上做了一題2187,限時3s。
算法主要耗時在多次求不同整數的平方。
當用pow函數求時,超時;
而直接乘才232ms。
相差也太大了吧。
于是就寫了一段代碼來測試pow的性能
首先產生10000個隨機整數,然后重復1000次求整數的平方
#include <iostream>
#include <cmath>
#include <ctime>
using Namespace stdnamespace std;
const int MAX = 10000;
int a[MAX];
int main()
{
int i, j, n = MAX;
int rep = 1000; //重復次數
clock_t beg, end;
for(i = 0; i < n; i++)
a[i] = rand() % 20000 - 10000; //-10000 <= a[i]< 10000
cout<<"test a[i]*a[i]"<<endl;
beg = clock();
for(j = 0; j < rep; j++)
for(i = 0; i < n; i++)
a[i] * a[i];
end = clock();
cout<<"time: "<<end - beg<<"ms"<<endl;
cout<<"test pow(a[i], 2.0)"<<endl;
beg = clock();
for(j = 0; j < rep; j++)
for(i = 0; i < n; i++)
pow(a[i], 2.0);
end = clock();
cout<<"time: "<<end - beg<<"ms"<<endl;
return 0;
}
下面是測試結果:
test a[i]*a[i]
time: 31ms
test pow(a[i], 2.0)
time: 2828ms
所以下次遇到類似情況不再用pow函數了……


