c++学习笔记4:chrono 计时

要获取代码运行的时间,一个比较好的方式是使用chrono。

看例子,在两次获取时间的代码中间,休眠1s

#include <iostream>
#include <chrono>
#include <thread>

int main() {
	using namespace std::literals::chrono_literals;

	auto start = std::chrono::high_resolution_clock::now();

	std::this_thread::sleep_for(1s);

	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秒:

1.00451s

再看forloop打印100次的时间:

#include <iostream>
#include <chrono>
#include <thread>

struct Timer {
	std::chrono::time_point<std::chrono::steady_clock> start, end;
	std::chrono::duration<float> duration;

	Timer(){
		start = std::chrono::high_resolution_clock::now();
	}

	~Timer() {
		end = std::chrono::high_resolution_clock::now();
		duration = end - start;
		float ms = duration.count()*1000.0f;
		std::cout << "Timer took " << ms << "ms" << std::endl;
	}
};

void func() {
	Timer timer;

	for (int i = 0;i < 100;i++)
		std::cout << "hello" << std::endl;
}

int main() {
	func();

	std::cin.get();
}

代码做了结构化调整,将相关功能都提取到一个结构中,然后在func函数中创建一个Timer,当func执行完毕,Timer自动析构。输出为:

hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Timer took 105.268ms

如果去掉std::cout << "hello" << std::endl; 语句的std::endl,再看执行时间:

lohelloTimer took 4.839ms

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值