C++中一个计算程序运行时间的工具类

此工具类为单例模式,通过调用其方法能够计算程序的运行时间。

timeHelper.h

<span style="font-size:18px;">#include <time.h>
#include <iostream>
class timeHelper
{
private:
	clock_t tick_start;
	clock_t tick_stop;
	timeHelper(){} //构造函数私有化
	static timeHelper *m_pInstance;
	class CGarbo   //它的唯一工作就是在析构函数中删除CSingleton的实例  
	{
	public:
		~CGarbo()
		{
			if (timeHelper::m_pInstance)
				delete timeHelper::m_pInstance;
		}
	};
	static CGarbo Garbo;  //定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数 
public:
	static timeHelper * GetInstance();//获取实例
	void  start();//开始计算时间
	void  stop(); //停止计算时间
	double getInterval();//得到间隔
	void outputInterval();//输出间隔
};</span>

timeHelper.cpp

#include "timeHelper.h"

timeHelper *timeHelper::m_pInstance = NULL;
/************************************************************************/
/* 开始计时                                                             */
/************************************************************************/
void timeHelper::start(){
	tick_start = clock();
}
/************************************************************************/
/* 结束计时                                                             */
/************************************************************************/
void timeHelper::stop(){
	tick_stop = clock();
}
/************************************************************************/
/* 得到运行时间                                                         */
/************************************************************************/
double timeHelper::getInterval(){
	double time_interval = tick_stop - tick_start;
	tick_start = 0;
	tick_stop = 0;
	return time_interval;
}
/************************************************************************/
/* 输出运行时间                                                         */
/************************************************************************/
void timeHelper::outputInterval(){
	printf("running_time_ms:\n");
	printf("dt = %lf ms\n", getInterval());
}
/************************************************************************/
/* 得到单例                                                             */
/************************************************************************/
timeHelper * timeHelper::GetInstance()
{
	if (m_pInstance == NULL)  //判断是否第一次调用  
		m_pInstance = new timeHelper();
	return m_pInstance;
}


使用方式如下:

#include "timeHelper.h"

int main(int argc, char* argv[])
{

	timeHelper::GetInstance()->start();
        /*执行操作自己的*/
	timeHelper::GetInstance()->stop();
	timeHelper::GetInstance()->outputInterval();
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值