C++如何获取一段程序运行时间

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++总结

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值