您的位置:首页 > 其它

关于算法运行时间的简单测试

2017-08-01 00:34 246 查看
文章将会提到两种测时办法,clock_t 与time_t,其中由于前者单位是毫秒ms而后者单位是秒s,故在精度上前者胜出,用于测时更加精准。

这个测试算法可以反映处算法的运行效率,因此可以用于比较算法设计的优劣。

//计时,可用于比较算法的效率
//其中第一种办法精确度更高,前者clock_t以ms为单位,因为CLOCKS_PER_SEC数值为1000,1s/1000 = 1ms; 而后者time_t直接以秒s为单位。
//不过两者都是——若调用失败,则返回-1。
//Created by Ant on 07/25/2017
//

#include <iostream>
#include <ctime>
using namespace std;

int main() {

int n = 1000, t = 3;

while(t--){
cout << "n = " << n << endl;

// 显示近似 O(N^2)的时间复杂度
clock_t startTime = clock(); //开始时刻

for (int i = 1; i <= n; ++i)
for (int j = i; j <= n; ++j ); //i的初值别设置为0,否则开始时j将会一直为0死循环

clock_t endTime = clock(); //结束时刻

//输出时间段,并转化单位为秒s
cout << "startTime = " << startTime << '\t' << "endTime = " << endTime << endl;
cout << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl << endl;

n *= 10;
}
cout << endl;

int n1 = 1000, t1 = 3;
while (t1--) {
cout << "n1 = " << n1 << endl;

time_t startT = time(NULL); //开始时刻
for (int i = 1; i <= n1; ++i)
for (int j = i; j <= n1; ++j);
time_t endT = time(NULL); //结束时刻

cout << "startT = " << startT << '\t' << "endT = " << endT << endl;
cout << difftime(endT, startT) << "s" << endl << endl;

n1 *= 10;
}

return 0;
}



这是测试样例的运行结果如下:



喂丸待续……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  测时 算法效率