此工具类为单例模式,通过调用其方法能够计算程序的运行时间。
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();
}