数组求和(递归和循环)函数 时间性能测量(最差情形)
#include <stdio.h>
#include <time.h>
#define MAX_SIZE 1000
typedef struct
{
double duration;
long repetitions;
}times;
double sum_f(double list[], int n);
double sum_r(double list[], int n);
void timer(double(*sum)(double list[], int n), double list[], int n,
times *);
int main(void)
{
double list[MAX_SIZE];
times F,R;
printf("function repetitions time");
for(int n=100; n<=MAX_SIZE; n+=100)
{
for(int i=0; i<n; i++)
list[i]=n-i;
// for(int k=0; k<n; k++)
// printf("%f ", list[k]);
// printf("\n");
timer(sum_f, list, n, &F);
timer(sum_r, list, n, &R);
printf("\nF: array_size:%3d %d %6.15lf ", n, F.repetitions, F.duration);
printf("\nR: array_size:%3d %d %6.15lf \n", n, R.repetitions, R.duration);
}
return 0;
}
double sum_f(double list[], int n)
{
double tempsum=0;
for(int i=0; i<n; i++)
tempsum+=list[i];
return tempsum;
}
double sum_r(double list[], int n)
{
if(n) return sum_r(list, n-1)+list[n-1];
return 0;
}
void timer(double(*sum)(double list[], int n), double list[], int n,
times *x)
{
x->repetitions=0;
clock_t start=clock();
do{
x->repetitions++;
sum(list, n);
}while(clock()-start<3000);
x->duration=(double)(clock()-start/(3*CLOCKS_PER_SEC));
x->duration/=x->repetitions;
}
posted on 2017-12-31 22:12 MACHINE_001 阅读(131) 评论(0) 编辑 收藏 举报