该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
#include
#define count 100
int sum1();
int sum2();
int main()
{
int sum;
long int time1,time2,time;
struct timeval tv;
gettimeofday(&tv, NULL); //获取时间
time1=tv.tv_usec;
sum=sum1(count);//递归
printf("sum=%d\n",sum);
gettimeofday(&tv, NULL); //获取时间
time2=tv.tv_usec;
time = time2-time1;
printf("递归 use time:%ld\n",time);
gettimeofday(&tv, NULL); //获取时间
time1=tv.tv_usec;
sum=sum2(count);//循环
printf("sum=%d\n",sum);
gettimeofday(&tv, NULL); //获取时间
time2=tv.tv_usec;
time = time2-time1;
printf("循环 use time:%ld\n",time);
return 0;
}
int sum1(int n)
{
if(n == 1)
return 1;
else
return n + sum1(n-1);
}
int sum2(int n)
{
int sum = 0,i;
for(i = 1; i <= n; i++)
sum += i;
return sum;
}
这是测试循环与递归所用时间的测试代码,在linux上取系统时间以us来测试的