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

相关推荐
a东方青3 小时前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
XiaoyaoCarter4 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
galaxy_strive4 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
Darkwanderor4 小时前
c++STL-list的模拟实现
c++·list
Humbunklung5 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio
小乌龟不会飞5 小时前
gflags 安装及使用
c++·mfc·gflags 库
June`6 小时前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
AI+程序员在路上7 小时前
XML介绍及常用c及c++库
xml·c语言·c++
guoguo05247 小时前
vs2019及以后版本cmd指定编译环境文件的路径
c++
软行7 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展