C++获取程序运行时间(精确到纳秒&毫秒)

2022-12-09 15:31:47 2697人已围观 55已点赞 21人已收藏

简介本文介绍C++获取程序运行时间:可精确到纳秒、毫秒级时间。对于C++开发过程中计算某段代码的运行时间、提交代码性能有一定的参考价值。

话不多说,直接上代码,一键操作。

方式一

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;

// 算法示例
void Test()
{
	for (int i = 0; i < 10; i++)
	{
		std::cout << "C++实战网(www.cppszw.com)" << std::endl;
	}
}

int main()
{
	typedef std::chrono::high_resolution_clock Clock;
	auto t1 = Clock::now();// 计时开始
	Test();
	auto t2 = Clock::now();// 计时结束

	std::cout << "用时(纳秒):" << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << std::endl;
	//std::cout << "用时(毫秒):" << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() / 1e+6 << std::endl;
	//std::cout << "用时(秒):" << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() / 1e+9 << std::endl;
}

运行结果:

C++,运行时间

方式二

#include <iostream>
#include <windows.h>

// 算法示例
void Test()
{
	for (int i = 0; i < 10; i++)
	{
		std::cout << "C++实战网(www.cppszw.com)" << std::endl;
	}
}

int main()
{
	double start_time = GetTickCount();
	Test();
	double end_time = GetTickCount();
	double dSecond = end_time - start_time;
	std::cout << "用时(毫秒):" << dSecond << std::endl;
}

运行结果:

C++,运行时间

源码下载
  • 最近更新:   2022-06-16开发环境:   Visual Studio 2015
  • 源码大小:   14.26KB下载次数:  21 

更多为你推荐