当前位置: 首页 > java >正文

C++中chrono计时器的简单使用示例

在 C++ 中进行计时(benchmark、函数运行时间、程序耗时分析)非常常见,推荐使用 C++11 引入的 <chrono> 标准库,它简洁、跨平台、类型安全。


推荐方使用 <chrono> 标准库

#include <iostream>
#include <chrono>
#include <thread>  // 仅用于演示延迟int main() {// 获取起始时间点auto start = std::chrono::high_resolution_clock::now();// 模拟耗时任务std::this_thread::sleep_for(std::chrono::milliseconds(123));// 获取结束时间点auto end = std::chrono::high_resolution_clock::now();// 计算耗时,单位为毫秒auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);std::cout << "耗时: " << duration.count() << " ms" << std::endl;return 0;
}

支持的常见时间单位

单位类型表达方式
std::chrono::seconds
毫秒std::chrono::milliseconds
微秒std::chrono::microseconds
纳秒std::chrono::nanoseconds

只需更改 duration_cast 的类型即可:

std::chrono::duration_cast<std::chrono::microseconds>(end - start);

封装一个简单 Timer 类

class Timer {
public:Timer() { reset(); }void reset() {start_time = std::chrono::high_resolution_clock::now();}double elapsedMilliseconds() const {return std::chrono::duration<double, std::milli>(std::chrono::high_resolution_clock::now() - start_time).count();}double elapsedSeconds() const {return std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start_time).count();}private:std::chrono::high_resolution_clock::time_point start_time;
};

使用方式:

Timer t;
// ... some work
std::cout << "耗时: " << t.elapsedMilliseconds() << " ms" << std::endl;

进阶用法:用于函数运行时间统计

template<typename Func>
void benchmark(Func f, const std::string& name = "Function") {auto start = std::chrono::high_resolution_clock::now();f();auto end = std::chrono::high_resolution_clock::now();double ms = std::chrono::duration<double, std::milli>(end - start).count();std::cout << name << " 执行耗时: " << ms << " ms\n";
}

调用示例:

benchmark([](){std::this_thread::sleep_for(std::chrono::milliseconds(200));
}, "任务函数耗时");
http://www.xdnf.cn/news/475.html

相关文章:

  • CF1016赛后总结
  • 常见网络问题
  • 2025年第16届蓝桥杯嵌入式竞赛学习笔记(十四):RTC实时时钟
  • 算法--打表法
  • JS案例-基于Proxy的响应式数据
  • [密码学基础]国密算法深度解析:中国密码标准的自主化之路
  • 在已有的vue项目中使用vuex
  • 鸿蒙开发11-ARKUI框架
  • 谷歌称LLMs.txt类似于关键词元标签:SEO影响与应对策略
  • 提升电脑性能!Windows超级管理器,免费使用,功能全面!
  • 开启健康养生新旅程
  • 单片机毕业设计选题物联网计算机电气电子类
  • 数字孪生赋能管理系统,降本增效立竿见影
  • 使用Spring Validation实现参数校验
  • 使用 MicroPython 在 ESP32-S3 上驱动 WS2812 LED 彩虹灯
  • 第34讲|遥感大模型对比实战:SAM vs. CLIP vs. iSAM
  • Policy Gradient思想、REINFORCE算法,以及贪吃蛇小游戏(四)(完结)
  • 基于 Linux 环境的办公系统开发方案
  • 智能座舱架构与芯片 - 背景篇
  • 医院科研科AI智能科研支撑平台系统设计架构方案探析
  • 点云(Point Cloud)介绍
  • Cocos Creater打包安卓App添加隐私弹窗详细步骤+常见问题处理
  • 第33讲|遥感大模型在地学分类中的初探与实战
  • PyTorch :优化的张量库
  • 数据从辅存调入主存,页表中一定存在
  • websocket和SSE学习记录
  • 得物官网sign签名逆向分析
  • Qt QWidget介绍及学习方法路线分享
  • 服务治理-服务注册
  • 【记录】服务器安装ffmpeg