C++计时的两种方法以及时钟函数的一点说明
1、方法一
#include<time.h>//<ctime>也行
#include<iostream>
using namespace std;
int main()
{
long start=clock();//开始时间,单位毫秒
//测试程序
long end=clock();
cout<<endl<<"耗时:"<<end-start<<"ms"<<endl;
return 0;
}
2、方法二
#include<time.h>//用万能头文件也行
#include<iostream>
using namespace std;
int main()
{
clock_t start=clock();
//测试程序
clock_t end=clock();
cout <<"消耗"<<(double)(end-start)/CLOCKS_PER_SEC << "s" << endl;
return 0;
}
3、关于clock_t clock( void )说明
这个函数返回从“开启这个程序进程”到“程序中调用C++ clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。其中clock_t是用来保存时间的数据类型,在time.h文件中,我们可以找到对它的定义:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif
很明显,clock_t是一个长整形数。在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:
#define CLOCKS_PER_SEC ((clock_t)1000)
定义clock_t类型的常量为1000,也就是说频率为1000。用两次返回的次数之差除以固有频率就可以得到时间。
4、一个关于插入排序与希尔排序时间比较的例子
#include<iostream>
#include<stdlib.h>
#include<time.h>
#define N 10000
using namespace std;
void insertion_sort (int arr[],int length)
{//插入排序
int i,j;
for(i=1;i<length;i++)
{
int temp=arr[i];
for(j=i;j>0&&arr[j-1]>temp;j--)
{
arr[j]=arr[j-1];
}
arr[j]=temp;
}
}
void shellsort(int arr[],int n)
{//希尔排序
for(int gap=n/2;gap>0;gap/=2)
{
for(int i=gap;i<n;i++)
{
int temp=arr[i];
int j;
for(j=i;j>=gap&&arr[j-gap]>temp;j-=gap)
arr[j]=arr[j-gap];
arr[j]=temp;
}
}
}
int main()
{
int a[N];//几乎不消耗时间
for(int i=0;i<N;i++)//消耗约200ms
a[i]=rand()%N;
for(int i=0;i<N;i++)//消耗约5000ms
{
cout<<a[i]<<'\t';
if((i+1)%15==0) cout<<'\n';
}
cout<<endl<<endl;
clock_t start=clock();//clock返回当前次数
insertion_sort(a,N);// 消耗约112ms
//shellsort(a,N) ;//消耗约2ms
clock_t end =clock();
for(int i=0;i<N;i++)//消耗约4700ms
{
cout<<a[i]<<'\t';
if((i+1)%15==0) cout<<'\n';
}
cout<<endl<<"耗时:"<<(double)(end-start)/CLOCKS_PER_SEC<<"s"<<endl;
return 0;
}
时间复杂度:
- 插入排序:O(n^2)
- 希尔排序:O(n log n)
更多排序算法的笔记见我的另一篇博客。