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)
更多排序算法的筆記見我的另一篇博客。