选择排序时间测量程序(时间测量函数clock())

来源:互联网 发布:鹰眼实力知乎 编辑:程序博客网 时间:2024/05/26 15:54
#include<stdio.h>#include<time.h>#define MAX 1001#define SWAP(x,y,t) (t=x,x=y,y=t)int sort(int* a,int n){  int i,j,temp;  for(i=0;i<n;i++)    for(j=i;j<n;j++)      if(a[j]<a[i])        SWAP(a[j],a[i],temp);}int main(){//此程序输出结果全为零,因为测试的时间间隔太短了 //程序的测量误差是+-1个时钟周期(1S是1000个时钟周期),//开始与结束的//时间点必须远远大于一个时钟周期时才会输出正确结果;  int i,n,step=10;  int a[MAX];  double duration;  clock_t start;  printf("    n    time\n");  for(n=0;n<MAX;n+=step)  {    for(i=0;i<n;i++)      a[i]=n-i;    start=clock();    sort(a,n);    duration=((double)(clock()-start))/CLOCKS_PER_SEC;    printf("%6d    %lf\n",n,duration);      if(n==100)          step=100;  }}/*   n    time     0    0.000000    10    0.000000    20    0.000000    30    0.000000    40    0.000000    50    0.000000    60    0.000000    70    0.000000    80    0.000000    90    0.000000   100    0.000000   200    0.000000   300    0.000000   400    0.000000   500    0.000000   600    0.000000   700    0.015000   800    0.000000   900    0.000000  1000    0.000000  */

#include<stdio.h>  //选择排序时间测量程序#include<time.h>#define MAX 1001#define SWAP(x,y,t) (t=x,x=y,y=t)int sort(int* a,int n){  int i,j,temp;  for(i=0;i<n;i++)    for(j=i;j<n;j++)      if(a[j]<a[i])        SWAP(a[j],a[i],temp);}int main(){//此程序输出结果全为零,因为测试的时间间隔太短了 CLOCK 函数精确度不够  int i,n,step=10;  int a[MAX];  double duration;long count=0;  clock_t start,stop;   printf("    n    time\n");  for(n=0;n<MAX;n+=step)  {    start=clock();    count=0;        do    {      count++;//统计这个长度为n的数组被重复排序多少次;        for(i=0;i<n;i++)              a[i]=n-i;        sort(a,n);    }    while(clock()-start<1000);    duration=((double)(clock()-start)/CLOCKS_PER_SEC);    printf("%6d    %lf\n",n,duration/count);      if(n==100)          step=100;  }}/*          n    time     0    0.000000    10    0.000000    20    0.000002    30    0.000004    40    0.000006    50    0.000010    60    0.000014    70    0.000019    80    0.000025    90    0.000031   100    0.000038   200    0.000148   300    0.000330   400    0.000583   500    0.000918   600    0.001312   700    0.001779   800    0.002336   900    0.002997  1000    0.003690*/

0 0