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

相关推荐
散峰而望8 分钟前
【算法竞赛】栈和 stack
开发语言·数据结构·c++·算法·leetcode·github·推荐算法
不爱吃糖的程序媛32 分钟前
OpenHarmony 通用C/C++三方库 标准化鸿蒙化适配
c语言·c++·harmonyos
fqbqrr35 分钟前
2601C++,导出控制
c++
陌路201 小时前
日志系统7--异步日志的实现
c++
程序员Jared1 小时前
C++11—this_thread
c++·this_thread
mjhcsp1 小时前
C++ Manacher 算法:原理、实现与应用全解析
java·c++·算法·manacher 算法
Z1Jxxx1 小时前
0和1的个数
数据结构·c++·算法
朔北之忘 Clancy2 小时前
2020 年 6 月青少年软编等考 C 语言二级真题解析
c语言·开发语言·c++·学习·青少年编程·题解·尺取法
消失的旧时光-19432 小时前
C++ 中的 auto 与 nullptr:不是语法糖,而是类型系统升级
开发语言·c++
fpcc2 小时前
跟我学C++中级篇—C++17中的元编程逻辑操作
c++·模板编程