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

【Cherno C++】63、C++计时器的使用,第1张

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

一般用法
#include 
#include 
#include 
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 
#include 


class Timer
{
public:
	Timer()
	{
		// 对象创建时,记录一次时间
		start = std::chrono::high_resolution_clock::now(); 
	}
	~Timer()
	{
		// 对象销毁时,记录一次时间
		end = std::chrono::high_resolution_clock::now();   
		// 持续时间,默认是秒,必须调用.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;
	for (int i = 0; i < 100; i++)
	{
		std::cout << "Hello!\n"; //用\n的运行速度比endl快三分之一
	}
}

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

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/674935.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-19
下一篇 2022-04-19

发表评论

登录后才能评论

评论列表(0条)

保存