C++计时器

该代码示例展示了一个简单的C++类Timer,利用chrono库来测量代码段的执行时间。类在构造时开始计时,析构函数中停止计时并打印出以微秒和毫秒为单位的运行时间。在main函数中,对一个循环进行了计时以展示Timer类的用法。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <chrono>
class Timer
{
public:
	Timer(){
		m_StartTimePoint = std::chrono::high_resolution_clock::now();
	}
	~Timer(){
		stop();
	}
	void stop()
	{
		auto endTimePoint = std::chrono::high_resolution_clock::now();
		auto start = std::chrono::time_point_cast<std::chrono::microseconds>(m_StartTimePoint).time_since_epoch().count();
		auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTimePoint).time_since_epoch().count();
        auto duration = end-start;
        double ms = duration*0.001;
        std::cout<<"运行花费:"<<duration<<"微秒,"<<ms<<"毫秒"<<std::endl;
	}

private:
	std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTimePoint;
};

int main()
{
	long number =0;
	{
		Timer timer;
	
	    for (int i=0;i<10000000;i++) {
	      number+=1;
	    }	
	}
	
    std::cout << number << std::endl;
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值