算法分析中需要對各種算法進行性能測試,下面介紹兩種通用的測試方法,由於只用到標准c語言函數,所以在各種平台和編譯器下都能使用。
方法1:
clock()函數
開始計時:start = clock()
結束計時:end = clock()
start和end都是clock_t類型
結果(秒):time = (double)(end - start) / CLOCKS_PER_SEC
#include <iostream>
#include <cstdio>
#include <ctime>
#include <algorithm>
#include <functional>
using namespace std;
inline bool cmp(int a, int b)
{
return a > b;
}
const int n = 100000000;
int a[n];
int main()
{
clock_t start, stop;<SPAN style="WHITE-SPACE: pre"> </SPAN>//定義clock_t類型的start和end
for (int i = 0; i < n; ++i)
a[i] = i;
start = clock();
//sort(a, a + n, cmp); //開始計時
sort(a, a + n, greater<int>());<SPAN style="WHITE-SPACE: pre"> </SPAN>//中間是需要計時的代碼
stop = clock(); //結束計時
printf("%f\n", (double)(stop - start) / CLOCKS_PER_SEC);
return 0;
}
#include <iostream>
#include <cstdio>
#include <ctime>
#include <algorithm>
#include <functional>
using namespace std;
inline bool cmp(int a, int b)
{
return a > b;
}
const int n = 100000000;
int a[n];
int main()
{
clock_t start, stop; //定義clock_t類型的start和end
for (int i = 0; i < n; ++i)
a[i] = i;
start = clock();
//sort(a, a + n, cmp); //開始計時
sort(a, a + n, greater<int>()); //中間是需要計時的代碼
stop = clock(); //結束計時
printf("%f\n", (double)(stop - start) / CLOCKS_PER_SEC);
return 0;
}
這段代碼對排序中使用自己定義的函數和函數對象的速度進行測試,平均情況下還是函數對象的版本比較快。(當然這種測試不夠嚴謹,僅僅是演示一下計時的方法)
方法2:和上一種方法差不多,只是用時間函數。
time_t start, end;
start = time(NULL);
end = time(NULL);
time = (double)(end - start);