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的第二个模板参数不写时,即为秒级别时间。

相关推荐
端平入洛1 天前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马3 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼3 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx3 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX3 天前
020-C++之unordered容器
数据结构·c++