C++使用time.h库计算持续时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liaoyanyunde/article/details/83274679

一、使用click函数,精确到毫秒(推荐使用这种)

计算算法程序的执行时间,使用clock()函数,返回值是长整型long
函数原型为: clock_t clock(void);
其中clock_t的定义为:typedef long clock_t;说明 clock_t就是长整型

实际上这个函数返回的不是时间,这个函数只是一个计数器,时间每过千分之一秒(就是毫秒)就加1(这个定义在time.h中)
#define CLOCKS_PER_SEC 1000
这个数值不能增加,因为在标准C/C++中,最小的计时单位就是一毫秒。

#include <stdio.h>
#include <time.h>
using namespace std;
void myTime() {
	clock_t start = clock();
	cout<<"开始时间:"<<start<<endl;
	long i=100000000;
	while(i--);
	clock_t end = clock();
	cout<<"结束时间:"<<end<<endl;
	cout<<"算法执行持续时间:"<<end-start<<"毫秒"<<endl;
}
void main(){
	myTime();
}

二、使用time和difftime函数,精确到秒

time方法–获取当前时间戳

time方法用于获取日历时间,所谓的日历时间是指从一个时间点(例如:1970年1月1日0时0分0秒)到现在此时的秒数)到现在的秒数,其实就是个相对时间,也是当前的时间戳(到秒),跟一般的时间戳转换工具(如站长工具)的值相同
time_t time(time_t * timer);

time_t实际就是个long(32位长整形)或者__int64(VC中的扩展64位整形)或者long long(g++编译器中的扩展64位整形)
如下time_t的定义是在win32的环境下的定义:
typedef _W64 long __time32_t;
typedef __time32_t time_t;
在其他环境可能不同。

time_t * timer其实就是出参参数,函数返回值跟timer的值都是一样,都是当前的日历时间,
如果传入NULL或者0,则该函数返回值的就是当前的时间戳。

	time_t timer=12345678;
	time_t nowtime=time(&timer);
	cout<<timer<<endl;
	cout<<nowtime<<endl;
	cout<<time(0)<<endl;
	cout<<time(NULL)<<endl;
	cout<<time(nullptr)<<endl;

输出:

1540199258
1540199258
1540199258
1540199258
1540199258

difftime方法–比较两个时间戳之间的间隔

该函数返回的以秒计算的时间间隔是double类型的,但这并不说明该时间具有同double一样的精确度,这是由它的参数决定的(time_t是以秒为单位计算的)
double difftime(time_t _Time1, time_t _Time2)

计算持续时间:

#include <stdio.h>
#include <time.h>
using namespace std;
void myTime() {
	time_t start = time(NULL);
	cout<<"开始时间:"<<start<<endl;
	long i = 100000000;
	while(i--) ;
	time_t end = time(NULL);
	cout<<"结束时间:"<<end<<endl;
	cout<<"算法执行持续时间:"<<difftime(end,start)<<"秒"<<endl;
}
void main(){
	myTime();
}

猜你喜欢

转载自blog.csdn.net/liaoyanyunde/article/details/83274679