确定程序的运行时间,为此需要一个定时机制。本书使用c++函数clock()来测量时间,它用"滴答"数来确定。在头文件time.h中定义了常数CLOCK_PER_SEC,它记录仪每秒流逝的滴答数,并转换为秒。CLOCK_PER_SEC=1000,滴答一次约等于1毫秒
代码如下
#include<iostream>
#include<time.h>
using namespace std;
//插入排序
template<class T>
void insertionSort(T*a,int n){
for(int i=1;i<n;i++){
//把a[i]插入b[0:i-1]中
T t=a[i];
int j=i-1;//这里int下面就不用再int,要不然会造成混用
for(j=i-1;j>=0&&t<a[j];j--){a[j+1]=a[j];}
a[j+1]=t;
}
}
//导致插入排序出现最坏复杂度的程序
//误差在10%的测量程序
int main(){
int a[1000],step=10;
double clocksPerMillis=double(CLOCKS_PER_SEC)/1000;
cout<<"The worst-case time,in milliseconds,are"<<endl;
cout<<"n\tRepetition \t Total Tricks \tTime per Sort"<<endl;
//次数n=0,10,20,...100,200,300,...,1000
for(int n=0;n<=1000;n+=step){
//为实例特征n运行测量时间
long numberofRepetition=0;
clock_t startTime=clock();
do{
numberofRepetition++;
for(int i=0;i<n;i++)a[i]=n-i;
insertionSort(a,n);
}while(clock()-startTime<1000);
//重复时间运行,直到有足够时间流逝
double elapsedMillis=(clock()-startTime)/clocksPerMillis;
cout<<n<<'\t'<<numberofRepetition<<'\t'<<elapsedMillis<<'\t'<<elapsedMillis/numberofRepetition<<endl;
if(n==100)step=100;
}
return 0;
}
运行结果如下
The worst-case time,in milliseconds,are
n Repetition Total Tricks Time per Sort
0 93213740 1000 1.0728e-05
10 5883264 1007 0.000171163
20 1590610 1002 0.000629947
30 713474 1004 0.0014072
40 404020 1002 0.00248008
50 252185 1000 0.00396534
60 190344 1007 0.00529042
70 183574 1003 0.00546374
80 138440 1000 0.00722335
90 108173 1004 0.00928143
100 97116 1000 0.010297
200 23926 1000 0.0417955
300 11690 1006 0.0860565
400 6673 1002 0.150157
500 4008 1006 0.250998
600 2982 1000 0.335345
700 2201 1002 0.455248
800 1560 1006 0.644872
900 1323 1005 0.759637
1000 1050 1002 0.954286