方法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);