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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值