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

C++ 时间处理-统计函数运行时间

  • 1. 关键词
  • 2. 问题
  • 3. 解决思路
  • 4. 代码实现
    • 4.1. timecount.h
    • 4.2. timecount.cpp
  • 5. 测试代码
  • 6. 运行结果
  • 7. 源码地址

1. 关键词

C++ 时间处理 统计函数运行时间 跨平台

2. 问题

C++如何简单便捷地实现“函数运行时间的统计”功能?

3. 解决思路

  • 类的构造函数:会在对象初始化的时候被调用。
  • 类的析构函数:会在对象销毁的时候被调用。
  • 局部对象的生命周期:对象实例化(也就是初始化)时开始,退出作用域时结束。

4. 代码实现

4.1. timecount.h


#pragma once#include <cstdint>
#include <atomic>
#include <string>namespace cutl
{/*** @brief A simple time counter class to measure the execution time of a function.**/class timecount{public:/*** @brief Construct a new timecount object* The constructor will record the begin time of the function calling.* @param func_name*/timecount(const std::string &func_name);/*** @brief Destroy the timecount object* The desctructor will record the end time of the function calling and calculate the execution time.*/~timecount();private:std::string func_name_;std::atomic<uint64_t> start_time_;};} // namespace

4.2. timecount.cpp

#include "timecount.h"
#include "timeutil.h"
#include "strfmt.h"
#include "inner/logger.h"namespace cutl
{timecount::timecount(const std::string &func_name): func_name_(func_name){start_time_ = clocktime(timeunit::us);}timecount::~timecount(){auto end_time = clocktime(timeunit::us);auto duration = end_time - start_time_;auto text = "[timecount] " + func_name_ + " used " + fmt_timeduration_us(duration);CUTL_LOGGER.info("", text);}
} // namespace

5. 测试代码

#pragma once#include <iostream>
#include "timecount.h"
#include "common.hpp"void TestTimecount()
{PrintTitle("timecount");cutl::timecount tcount("TestTimecount");std::cout << "TestTimecount begin" << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "TestTimecount end" << std::endl;
}

6. 运行结果

=============================================timecount==============================================
TestTimecount begin
TestTimecount end
[2024-05-19 22:34:35.853][I]]0x7ff844a9b100](cutl)  [timecount] TestTimecount used 01s.004955us

7. 源码地址

更多详细代码,请查看本人写的C++ 通用工具库: common_util, 本项目已开源,代码简洁,且有详细的文档和Demo。

http://www.lryc.cn/news/353629.html

相关文章:

  • JAVA面试题大全(十五)
  • 使用python对指定文件夹下的pdf文件进行合并
  • Day50 | 309.最佳买卖股票时机含冷冻期 714.买卖股票的最佳时机含手续费 总结
  • Steam在连接至服务器发生错误/连接服务器遇到问题解决办法
  • kafka 工作流程文件存储
  • 贪心算法4(c++)
  • 【无标题】yoloV8目标检测与实例分割--目标检测onnx模型部署
  • 深入理解与防御跨站脚本攻击(XSS):从搭建实验环境到实战演练的全面教程
  • 初步认识栈和队列
  • 插件:NGUI
  • 网络爬虫原理及其应用
  • 串口中断原理及实现
  • 课时136:变量进阶_变量实践_高级赋值
  • 牛客网刷题 | BC99 正方形图案
  • 启动小程序F12窗口管理器
  • 完全背包之零钱兑换I
  • Flutter 中的 FittedBox 小部件:全面指南
  • Java的线程的使用
  • 行为型模式 (Python版)
  • vscode:如何解决”检测到include错误,请更新includePath“
  • 区块链会议投稿资讯CCF A--USENIX Security 2025 截止9.4、1.22 附录用率
  • vue实现可拖拽移动悬浮球
  • 立体库堆垛机的精密构造与功能(收藏版)
  • 算法提高之你能回答这些问题吗
  • C++-指针
  • Three.js 研究:2、如何让动画线性运动
  • z3-加法器实验
  • 解决git克隆项目出现fatal无法访问git clone https://github.com/lvgl/lvgl.git
  • Vue中引入组件需要哪三步
  • 到底该用英文括号还是中文括号?