栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 计算程序运行时间

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 计算程序运行时间

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

结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916901.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号