我试过实现两个方法递归和动态方法,并且都花了0秒,这意味着我的计算机中没有人更好或代码中有什么问题?这是这些方法
1 //递归
#include <stdio.h>
#include <time.h>
#include <iostream>
using std::cout;
void print(int n){
if (n<0) return ;
cout<<n<<" ";
print(n-1);
}
int main(){
int n=10;
time_t start,end;
double dif;
time(&start);
print(n);
time(&end);
dif=difftime(end,start);
printf("it took you %.21f seconds ",dif);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二种方法
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
void print (int n){
if (n<0) return ;
while (n>=0){
cout<<n--<<endl;
}
}
int main(){
int n=10;
double dif;
time_t start,end;
time(&start);
print(n);
time(&end);
dif=difftime(end,start);
printf("it took you %.21f seconds",dif);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二时钟分辨率不适合测量这种快速操作.
我建议您多次执行代码(类似于100万次; for为此使用循环),估计总时间,然后计算平均值.
这样您将获得更可靠的结果.
只是一个快速说明:我看到你cout在你的功能中使用.这是一个坏主意:cout通常大多数I/O操作对于其他操作来说都很慢.您的函数可能会花费大部分时间来打印值,而不是计算它.