【Cherno C++】63、C++计时器的使用

本文介绍了C++11中chrono库的使用,包括如何利用chrono进行精确的时间测量,如休眠1秒以及封装成Timer类来方便地计算函数执行时间。通过示例代码展示了chrono库在实际应用中的效果,例如100次Hello!输出所花费的时间约为40毫秒。
摘要由CSDN通过智能技术生成

C++11特性
关键库文件: < c h r o n o > <chrono> <chrono>

一般用法

#include <iostream>
#include <chrono>
#include <thread>
int main()
{
	using namespace std::literals::chrono_literals 	//休眠1s中的s,必须使用这个空间
	auto start = std::chrono::high_resolution_clock::now();  //当前时间
	std::this_thread::sleep_for(1s);						 //当前线程休眠1秒
	auto end = std::chrono::high_resolution_clock::now();	 //当前时间

	std::chrono::duration<float> duration = end - start;	 //时间差

	std::cout << duration.count() << "s" << std::endl;

	std::cin.get();
}

运行结果:1.00286s
分析:很接近1,但不绝对准确

封装作用域Timer类

#include <iostream>
#include <chrono>


class Timer
{
public:
	Timer()
	{
		// 对象创建时,记录一次时间
		start = std::chrono::high_resolution_clock::now(); 
	}
	~Timer()
	{
		// 对象销毁时,记录一次时间
		end = std::chrono::high_resolution_clock::now();   
		// 持续时间,默认是秒,duration对象的.count()时间值
		duration = end - start;
		float ms = duration.count() * 1000.0f;		
		std::cout << "Timer took" << ms << " ms " << std::endl; 
	}
public:
	std::chrono::time_point<std::chrono::steady_clock> start, end;
	std::chrono::duration<float> duration;
};

void Function()
{
	Timer timer;	// 出Function()作用域后自动输出时间并且销毁
	for (int i = 0; i < 100; i++)
	{
		std::cout << "Hello!\n"; //用\n的运行速度比endl快三分之一
	}
}

int main()
{
	Function(); 
	std::cin.get();
}

release下输出结果:100个Hello!,时间花费为 40.8741ms

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宗浩多捞

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值