class calcRunTime{
public:
calcRunTime(std::string t){
tag=t;
startTime = clock();
lastTime = clock();
}
void printTime(std::string t,std::string msg){
tag=t;
clock_t now_time=clock();
#ifdef ANDROID
double tim=(double)(now_time - lastTime)/ 1000.0;
if(tim>20)
ALOGE(" calcRunTime-- %s [%s]: %lf ms",t.c_str(),msg.c_str(),tim);
#else
printf(" calcRunTime-- %s [%s]: %lf ms",t.c_str(),msg.c_str(),(double)(now_time - lastTime)/ 1000.0);
#endif
lastTime = clock();
}
void restart(std::string t){
tag=t;
startTime=clock();
}
void setTag(std::string t){
tag=t;
}
~calcRunTime(){
lastTime=startTime;
printTime(tag,"end of timing, total time");
}
static calcRunTime* static_ctr_p;
private:
std::string tag="";
clock_t startTime,endTime,lastTime;
};
//方式一: 需要在同一个语句块成对出现,多线程(推荐)
#define CALC_TIME_START(index) {calcRunTime crt##index(__FUNCTION__);
#define CALC_TIME_SPAN(index,msg) crt##index.printTime(__FUNCTION__,msg);
#define CALC_TIME_RESET(index) crt##index.restart(__FUNCTION__);
#define CALC_TIME_END(index) crt##index.setTag(__FUNCTION__);}
//方式2: 跨程序块执行,跨线程全局变量需要做维护,多线程算了
#define CALC_TIME_START1(crt_ptr) crt_ptr=new calcRunTime(__FUNCTION__);
#define CALC_TIME_SPAN1(msg,crt_ptr) crt_ptr->printTime(__FUNCTION__,msg);
#define CALC_TIME_RESET1 crt_ptr->restart(__FUNCTION__);
#define CALC_TIME_END1(crt_ptr) crt_ptr->setTag(__FUNCTION__);delete crt_ptr;
//方式3: 任意地方使用,多线程算了
#define CALC_TIME_START2 if(calcRunTime::static_ctr_p== nullptr)calcRunTime::static_ctr_p=new calcRunTime(__FUNCTION__);
#define CALC_TIME_SPAN2(msg) calcRunTime::static_ctr_p->printTime(__FUNCTION__,msg);
#define CALC_TIME_RESET2 calcRunTime::static_ctr_p->restart(__FUNCTION__);
#define CALC_TIME_END2 calcRunTime::static_ctr_p->setTag(__FUNCTION__);delete calcRunTime::static_ctr_p; calcRunTime::static_ctr_p=nullptr;
使用:
//方式1
{
CALC_TIME_START(0);
...
CALC_TIME_SPAN(0,"test1")
...
CALC_TIME_END(0)
}
//方式2
calcRunTime* ctr_p;
CALC_TIME_START1(ctr_p);
{
...
CALC_TIME_SPAN1("test2",ctr_p)
...
CALC_TIME_END1(ctr_p)
}
//方式3
calcRunTime* calcRunTime::static_ctr_p= nullptr;
//任意位置
CALC_TIME_START2
CALC_TIME_SPAN2("test3")
CALC_TIME_END2
结果



