关于算法运行时间的简单测试
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;
}
这是测试样例的运行结果如下:
喂丸待续……
这个测试算法可以反映处算法的运行效率,因此可以用于比较算法设计的优劣。
//计时,可用于比较算法的效率
//其中第一种办法精确度更高,前者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;
}
这是测试样例的运行结果如下:
喂丸待续……
相关文章推荐
- 关于测试程序运行时间
- 关于测试程序运行时间
- C-简单的算法时间测试
- JS简单测试循环运行时间的方法
- 简单的测试程序运行时间,避免输入干扰
- 动态测试方法运行时间的工具BTrace的简单应用
- 【算法与数据结构】关于代码运行时间复杂度的计算方法
- <编程>比较两种素数表生成算法+计算程序运行时间+通过CMD重定向测试程序
- 每个程序员都应该知道的14个数字(关于算法运行时间的)
- 简单的测试java代码运行时间
- USACO1.5Superprime Rid[附带关于素数算法时间测试]
- 如何精确计算出一个算法的CPU运行时间
- 算法运行时间分析
- java.util.concurrent多线程简单demo及计算多线程程序运行时间
- 描述一个运行时间为O(nlgn)的算法,使之能在给定一个由n个整数构成的集合S和另一个整数 X 时,判断出S中是否存在有两个其和刚好等于 X 的元素。
- 简单常识——关于 STL 算法
- 关于时间,日期,星期,月份的算法(Java中Calendar的使用方法)
- 测试程序运行时间的三种方法
- 关于归并排序运行时间的证明
- VC程序运行时间测试函数