C++如何获取一段程序运行时间
time.h中定义了计时函数:
clock_t clock();
这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)
其中,clock_t是记录时间的数据类型,time.h中对它的定义为:
typedef long clock_t;
一般和CLOCKS_PER_SEC一起用来计算以秒(s)为单位的运行时间:
double deltaT=clock()*1.0/CLOCKS_PER_SEC;
其中,time.h中对CLOCKS_PER_SEC的定义为:
/* Clock ticks macro - ANSI version */
#define CLOCKS_PER_SEC 1000
下面是测试代码,获取不同排序算法的运行时间:
#include<iostream>
#include<ctime>
#define random(x) rand()%(x) // 随机函数
using namespace std;
void InsertSort(int arr[], int len); // 插入排序
void BubbleSort(int arr[], int n); // 冒泡排序
void QuickSort(int arr[], int first, int end); // 快速排序
int OnceSort(int arr[], int first, int end); //
int main(){
clock_t startTime,endTime; // 记录运行时刻
const unsigned N=4000;
int numbers[N];
srand((int)time(0));
for (int i = 0; i < N; i++){
numbers[i]=random(10000); // 生成随机数数组,用于排序
}
startTime=clock(); // 开始时刻
InsertSort(numbers,N); // 排序
endTime=clock(); // 结束时刻
cout<<"插入排序:"<<(endTime-startTime)*1.0/CLOCKS_PER_SEC<<" s"<<endl; // endTime-startTime:开始到结束的时间长度,即排序的时间
startTime=clock();
BubbleSort(numbers,N);
endTime=clock();
cout<<"冒泡排序:"<<(endTime-startTime)*1.0/CLOCKS_PER_SEC<<" s"<<endl;
startTime=clock();
QuickSort(numbers,0,N-1);
endTime=clock();
cout<<"快速排序:"<<(endTime-startTime)*1.0/CLOCKS_PER_SEC<<" s"<<endl;
system("pause");
return 0;
}
(上述代码不包括排序算法的定义,演示工程)
运行结果:
参考:
C++中如何记录程序运行时间
C++ time.h 库详解
常见排序算法C++总结