c++11 利用chrono 计算代码执行时间

前言

在测试自己代码性能的时候都想知道这段代码执行了多长时间,方法很多,此次是利用chrono来实现。

比较简单,单纯记录一下。

直接上代码。

#include <iostream>
#include <chrono>

int main(int argc, char** argv)
{
	auto start = std::chrono::system_clock::now();

	/*需要计算运行时间地方*/
	std::cout << "Test" << std::endl;			

	auto end = std::chrono::system_clock::now();

	/*微秒单位*/
	auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();

	/*方式1*/
	double sec1 = duration * 0.000001; /*微秒单位*/	
	std::cout << sec1 << "s" << std::endl;

	/*方式2*/
	double sec2 = static_cast<double>(duration) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den;
	std::cout << sec2 << "s" << std::endl;
}

调试输出

结束

每天学习一点点.

posted @ 2021-07-10 15:52  想想就很离谱  阅读(888)  评论(0编辑  收藏  举报