C++计算程序运行时间

引言

有时候我们需要简单计算下程序的运行时间,但又不想借助工具,而是简单的几行代码来粗略计算下时间,话不多说我们直接开始吧。

chrono库使用

C++11中可以通过该库来实现,示例代码如下:

cpp 复制代码
#include <iostream>
#include <chrono>

void func() {
	int arr[1000][100];
	for (int j = 0; j < 100; ++j) {
		for (int i = 0; i < 1000; ++i) {
			arr[i][j] = 1;
		}
	}
}

int main() {
  auto beforeTime = std::chrono::steady_clock::now();
  func();
  auto afterTime = std::chrono::steady_clock::now();
  double duration_millsecond = std::chrono::duration<double, std::milli>(afterTime - beforeTime).count();
  std::cout << "total cost " << duration_millsecond << "ms" << std::endl;
}

执行结果如下:

bash 复制代码
total cost 0.460439ms

如果我们多处地方都要计算执行时间,那就要重复去写好几遍这段代码,不太方便。所以可以简单封装下:

cpp 复制代码
#include <iostream>
#include <chrono>

template<class T>
inline void costTime(void(*f)(), const std::string& info, const std::string& unit)
{
  auto beforeTime = std::chrono::steady_clock::now();
  f(); 
  auto afterTime = std::chrono::steady_clock::now();
  double duration_millsecond = T(afterTime - beforeTime).count();
  std::cout << info << " total cost " << duration_millsecond << unit << std::endl;
}

// 计算秒数
inline void costTimeBySec(void(*f)(), const std::string& info)
{
	costTime<std::chrono::duration<double>>(f, info, "s");
}
// 计算毫秒数
inline void costTimeByMs(void(*f)(), const std::string& info)
{
	costTime<std::chrono::duration<double, std::milli>>(f, info, "ms");
}
// 计算微秒数
inline void costTimeByUs(void(*f)(), const std::string& info)
{
	costTime<std::chrono::duration<double, std::micro>>(f, info, "us");
}
// 计算纳秒数
inline void costTimeByNs(void(*f)(), const std::string& info)
{
	costTime<std::chrono::duration<double, std::nano>>(f, info, "ns");
}
// 以上接口也可以封装到头文件,下次使用直接包含即可。

// 以下函数实现就都不写了
void func(); 
void func2(int n);
int func3(int n, int m); 

int main() {
	costTimeBySec(func, "func");
	costTimeByMs([](){ func2(1); }, "func2(1)"); // 传入lambda表达式
	costTimeByUs([](){ func3(1, 2); }, "func3(1, 2)"); // 传入lambda表达式
}

控制时间粒度的模板参数如下:

模板参数 级别
std::milli 毫秒
std::micro 微秒
std::nano 纳秒

duration的第二个模板参数不写时,即为秒级别时间。

相关推荐
wangjialelele15 分钟前
二刷C语言后,一万字整理细碎知识点
c语言·开发语言·数据结构·c++·算法·cpp
mjhcsp18 分钟前
P3145 [USACO16OPEN] Splitting the Field G(题解)
开发语言·c++·算法
空空潍19 分钟前
hot100-合并区间(day14)
c++·算法·leetcode
是娇娇公主~22 分钟前
算法——【最大子数组和】
数据结构·c++·算法
XH华1 小时前
备战蓝桥杯,第一章:C++入门
c++·蓝桥杯
Sheep Shaun1 小时前
深入理解AVL树:从概念到完整C++实现详解
服务器·开发语言·数据结构·c++·后端·算法
XH华1 小时前
备战蓝桥杯,第二章:C++语言的输入输出(上)
开发语言·c++·蓝桥杯
C++ 老炮儿的技术栈1 小时前
Qt中自定义 QmyBattery 电池组件开发
c语言·开发语言·c++·windows·qt·idea·visual studio
Howrun7771 小时前
Linux_C++_日志实例
linux·运维·c++
梵尔纳多1 小时前
第一个 3D 图像
c++·图形渲染·opengl