今天在学习浙大的数据结构课程,陈越老师让我们写代码来比较迭代和递归的性能差别,遂使用了ctime
or time.h
中的clock
函数来计算程序运行耗时。
方法
#include<ctime>
int main(){
clock_t start, finish; // 用来保存当前时钟的变量类型
start = clock(); // 调用clock函数获取当前时钟
.....
finish = clock();
double duration = (double)(finish - start) / CLOCKS_PER_SEC // CLOCKS_PER_SEC为定义在ctime中的常量
}
示例
比较递归与迭代的printN函数的性能:
#include<iostream>
#include<ctime>
#include<vector>
using namespace std;
void printN_v1(int n){
for (int i = 1; i <= n; i++){
cout << n;
}
cout << endl;
}
void printN_v2(int n){
if (n){
printN_v2(n-1);
cout << n;
}
cout << endl;
}
int main(){
int N[] = {10, 100, 1000, 10000}; // 测试数据
double duration;
vector<double> t1; // 迭代耗时
vector<double> t2; // 递归耗时
clock_t start, finish;
for (int i = 0; i < 4; i++){
start = clock();
printN_v1(N[i]);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
t1.push_back(duration);
start = clock();
printN_v2(N[i]);
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
t2.push_back(duration);
}
cout << endl << " Iteration recursion" << endl;
for (int i = 0; i < t1.size(); i++){
cout << N[i] << ": " << t1[i] << " " << t2[i] << endl;
}
return 0;
}