关于计算程序耗时的几个方法

2023-05-16

1. 一个来自r3live的timer tool工具:

一个功能丰富的头文件"tools_timer.hpp":


#ifndef __TIME_TICKER_HPP__
#define __TIME_TICKER_HPP__

#define TOOLS_TIMER_VERSION       "V2.0"
#define TOOLS_TIMER_VERSION_INFO  "Add timer logger"

#include <chrono>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <thread>
#include <time.h>
namespace Common_tools // Commond tools
{

static std::chrono::time_point< std::chrono::system_clock > timer_now()
{
    return std::chrono::system_clock::now();
}

static std::chrono::time_point< std::chrono::system_clock > g_commont_tools_timer_first_tic =  std::chrono::system_clock::now();

static inline double timer_tic_ms()
{
  std::chrono::duration<double> time_diff(timer_now() - g_commont_tools_timer_first_tic);
  return time_diff.count()*1000.0;
}

static inline double timer_tic()
{
  std::chrono::duration<double> time_diff(timer_now() - g_commont_tools_timer_first_tic);
  return time_diff.count();
}

static inline std::string get_current_date_str()
{
    const time_t     t = time( NULL );
    const struct tm *tmp = localtime( &t );
    char szDate[ 256 ];
    strftime( szDate, 80, "%Y/%m/%d", tmp );
    return std::string( szDate );
}

static inline std::string get_current_time_str( )
{
    const time_t     t = time( NULL );
    const struct tm *tmp = localtime( &t );
    char             szTime[ 256 ];
    strftime( szTime, 80, "%H:%M:%S", tmp );
    return std::string (szTime) ;
}

static inline std::string get_current_date_time_str( )
{
    const time_t     t = time( NULL );
    const struct tm *tmp = localtime( &t );
    char             szTime[ 256 ];
    char             szDate[ 256 ];
    strftime( szTime, 80, "%H:%M:%S", tmp );
    strftime( szDate, 80, "%Y/%m/%d", tmp );
    return (std::string (szDate) + " " + std::string(szTime)) ;
}

class Timer
{
  public:
    typedef std::map< std::string, std::chrono::time_point< std::chrono::system_clock > >           Map_string_timepoint;
    typedef std::map< std::string, std::chrono::time_point< std::chrono::system_clock > >::iterator Map_string_timepoint_it;
    // typedef std::map<std::string, double> Map_string_timepoint;
  private:
    Map_string_timepoint m_map_str_timepoint;
    char m_temp_char[4096];
    int  m_if_with_threadid = 1;
  public:

    Map_string_timepoint_it find_timepoint( const std::string &str )
    {
        Map_string_timepoint_it it = m_map_str_timepoint.find( str );
        if ( it == m_map_str_timepoint.end() )
        {
            m_map_str_timepoint.insert( std::make_pair( str, timer_now() ) );
            return m_map_str_timepoint.find( str );
        }
        else
        {
            return it;
        }
    }
  
    Timer()
    {
        ( find_timepoint( std::string( " " ) ) )->second = timer_now();
    }

    std::string get_thread_id_str()
    {
      if(m_if_with_threadid)
      {
        std::stringstream ss;
        ss << std::this_thread::get_id();
        //cout << "Id =" << std::this_thread::get_id() << endl;
        return  ss.str();
      }
      else
      {
        return std::to_string(0);
      }
    }


    uint64_t get_thread_id()
    {
        return std::stoull(get_thread_id_str());
     }


    void tic( std::string str = std::string( " " ) )
    {
      find_timepoint( str.append(  get_thread_id_str()  ) )->second = timer_now();
    }

    double toc( std::string str = std::string( " " ), int if_retick = 1 )
    {

        Map_string_timepoint_it it = find_timepoint( str.append(  get_thread_id_str() ) ) ;

        std::chrono::duration<double> time_diff = timer_now() - it->second;
        if ( if_retick )
        {
            it->second = timer_now();
        }
        return time_diff.count() * 1000;
        ;
    }

    std::string toc_string( std::string str = std::string( " " ), int if_retick = 1 )
    {

        sprintf( m_temp_char, "[Timer](%s): %s cost time = %.2f ms ",  get_thread_id_str().c_str(), str.c_str(), toc( str, if_retick ) );
        return std::string( m_temp_char );
    }
};


struct Cost_time_logger
{
  std::map<std::string, float> m_map_item_cost_time; 
  std::map<std::string, std::vector< float > > m_map_item_statics;
  FILE * m_fp =  nullptr;
  std::string SPLIT_NOTATION = std::string(":");
  Cost_time_logger(){};
  Cost_time_logger(std::string file_name) 
  {
    init_log(file_name);
  };
  void init_log(std::string file_name)
  {
    m_fp = fopen(file_name.c_str(), "w+");
  }

  void record(const std::string &item,const float & cost_time)
  {
    m_map_item_cost_time[item] = cost_time;
    m_map_item_statics[item].emplace_back(cost_time);
  }

  void record( Common_tools::Timer & timer, const std::string &item)
  {
    record( item, timer.toc(item, 0));
  }

  void flush()
  {
    if (m_fp != nullptr)
    {
      for (std::map<std::string, float>::iterator it = m_map_item_cost_time.begin(); it != m_map_item_cost_time.end(); it++)
      {
        fprintf(m_fp, "%s%s%.3f ", it->first.c_str(), SPLIT_NOTATION.c_str(), it->second);
      }
      fprintf(m_fp, "\r\n");
      fflush(m_fp);
    }
  };

  void flush_d()
  {
    if (m_fp != nullptr)
    {
      for (std::map<std::string, float>::iterator it = m_map_item_cost_time.begin(); it != m_map_item_cost_time.end(); it++)
      {
        fprintf(m_fp, "%s%s%d ", it->first.c_str(), SPLIT_NOTATION.c_str(), (int)it->second);
      }
      fprintf(m_fp, "\r\n");
      fflush(m_fp);
    }
  };

};

} // namespace Common_tools

#endif

使用案例:

    Common_tools::Timer tim;
    tim.tic("undistort");
    std::this_thread::sleep_for(std::chrono::microseconds(50)); //50微秒
    double undistort_cost = tim.toc("undistort");
    cout << "undistort cost " << undistort_cost  " ms" << endl;

单位是毫秒。

2.omp_get_wtime函数

omp_get_wtime函数可以返回从某个特殊点所经过的时间,单位秒

#include <omp.h>

CMakeLists.txt 添加:

set(CMAKE_C_STANDARD 99)
 
FIND_PACKAGE( OpenMP REQUIRED)
if(OPENMP_FOUND)
    message("OPENMP FOUND")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
	double t1 = omp_get_wtime();
	//************
	double t3 = omp_get_wtime();
	std::cout<<"[ Process ]: Time: "<<t3 - t1<<std::endl;

3. high_resolution_clock

	auto startTime = std::chrono::high_resolution_clock::now(); 
	// do something ...
	auto endTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - startTime).count();
	auto timeuse = endTime * 0.001;
	printf("Function Used %f ms", timeuse);

4.最基础std::clock()

slam十四讲中第三讲有用到。

#include<ctime>
int main()
{
    auto start = std::clock();
    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    auto end = std::clock();
    std::cerr << "耗时" << std::difftime(end, start) << "ms" << std::endl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于计算程序耗时的几个方法 的相关文章

  • C++为什么要学习STL和Boost库

    最近一年我电话面试了数十位 C 43 43 应聘者 xff0c 惯用的暖场问题是 工作中使用过 STL 的哪些组件 xff1f 使用过 Boost 的哪些组件 xff1f 得到的答案大多集中在 vector map 和 shared ptr
  • 智能硬件新产品开发逻辑

  • 移动机器人入门介绍

    移动机器人技术应用 xff1a 天上飞的 xff0c 水里游的 xff0c 地上跑的 xff0c 都可以应用移动机器人领域的技术 比如说 xff0c 1 工业机器人 xff0c 搬运机器人 xff08 AGV xff09 xff1b 2 商
  • 占据栅格地图(occupancy grid maps) -- 二值贝叶斯滤波应用

    其实 xff0c 我想讲的关键点是二值状态的最优估计问题 xff0c 而不仅仅是栅格地图 Anyway xff0c that is a good example 机器人的地图表示方式有多种 xff0c 如拓扑地图 特征地图 直接表征法 栅格
  • 粒子滤波实现及推导

    一 应用 example xff1a 机器人全局定位 粒子滤波实现过程解读 二 推导 从贝叶斯到粒子滤波 三 工程化细节探讨 这是草稿 xff0c 待完善
  • 卫星信号的上行下行学习笔记

    gt gt gt gt gt gt 我的博客目录导航 最近被卫星电视信号的发射接收过程弄的头疼 xff0c 于是潜心找了本书 卫星电视接收DIY 细细看看下 1 地面信号上星 以前在家弄个 锅 看看电视 xff0c 电视里主持人录节目 xf
  • 信息与不确定性

    最近学习了吴军的 信息论40讲 xff0c 深有感触 xff0c 有感而发 xff01 本博文想要给你传递 xff08 或者说洗脑 xff09 两个主要观点 xff1a 信息是可以量化的 xff0c 用事件的不确定性表示 xff0c 增加相
  • AlexeyAB/darknet (YOLO)的编译 和 作为动态库进行使用 以及 训练 自定义 数据(检测网络和分类网络)

    ubuntu 编译 https github com AlexeyAB darknet 这个库很贴心了 xff0c 当然 xff0c 主要是 darknet的实现也很硬核 xff0c 自带图像编解码 xff0c 各种造轮子 文档 把 各种用
  • LoRa和NB-IoT有什么区别?LoRa的优势在哪些方面?

    对于LoRa技术 xff0c 行业内人士都不会陌生 xff0c 它也经常会被拿来和NB IoT技术比较 作为低功耗广域网 xff08 LPWAN xff09 的新兴技术 xff0c 两种技术都备受关注 对于LoRa技术 xff0c 行业内人
  • Source Insight 4.0最好看的主题

    推荐一款sourceinsight主题 xff0c 4 0适用 xff0c 配色本人觉得非常舒服 使用方法 xff1a 1 安装Sourceinsight 2 安装字体 xff1a YaHei Consolas Hybrid 1 12 tt
  • Notepad++最好看的主题

    Notepad 43 43 最好看的主题 xff0c 收藏了很久 xff0c 现在拿出来和大家分享 配色如下 xff1a 使用方法 xff1a 1 安装Notepad 43 43 2 将KamiTheme xml放到 Notepad 43
  • DTLS协议中client/server的认证过程和密钥协商过程

    1 DTLS介绍 1 1 DTLS的作用 互联网先驱们最开始在设计互联网协议时主要考虑的是可用性 xff0c 安全性是没有考虑在其中的 xff0c 所以传输层的TCP UDP协议本身都不具备安全性 SSL TLS协议是基于TCP socke
  • Ubuntu18.04 实现串口通信

    最近由于项目需要 xff0c 研究了关于在ubuntu下串口通信的功能实现 期间遇到一些问题 xff0c 跟大家分享下 1 代码 comm service h ifndef comm service h define comm servic
  • [STM32] 串口数据帧处理(第一弹)

    文章目录 1 串口使用的常用场景2 字节帧处理总结 1 串口使用的常用场景 使用串口的主要目的是实现数据的交互 xff0c 数据的交互的方法脱身于常用的场景 这里描述一个比较典型的场景 xff1a MCU作为主控制器通过串口和外部的设备或者
  • 串口编程—(1)串口基本知识

    串口是用来干什么的 xff1f 串行接口 简称串口 xff0c 也称 串行通信 接口或 串行通讯接口 xff08 通常指 COM接口 xff09 xff0c 是采用 串行通信 方式的扩展接口 串行接口 Serial Interface 是指
  • C语言操作redis数据库

    文章目录 1 开发环境2 C语言redis库 hiredi安装配置2 1 下载并且解压hiredis2 2 hiredis安装 3 hiredis简单测试4 运行出错解决办法5 验证5 1 运行程序5 2 redis客户端验证 1 开发环境
  • 5.0 NuttX File System

    转载请注明出处 xff1a 5 0 NuttX File System Alvin Peng的博客 CSDN博客 文章均出自个人理解 前言 前一段时间折腾了几个驱动 xff08 PWM Serial I2C xff09 xff0c 这次来折
  • 使用cmake构建一个大型项目框架

    文章目录 使用CMake构建一个大型项目工程1 大型工程目录结构介绍1 1 工程目录结构介绍1 2 工程目录说明 xff08 我是这样设计的 xff0c 你们也可以参考类似这样设计 xff09 1 3 最外层CMakeLists txt说明
  • github下载加速的几种方法

    文章目录 1 github加速的几种办法1 1 把github的代码 xff0c 转到码云上1 2 有人做了github的代下载网站 xff0c 可以从上面进行下载1 3 使用cnpmjs镜像进行加速1 4 使用国外服务器进行搭桥 2 总结
  • EasyLogger的代码解读和移植(linux和stm)

    文章目录 1 EasyLogger目录结构分析 2 EasyLogger之docs查看总结 2 1 EasyLogger之docs查看 2 1 2 api gt kernel md文档 2 1 3 port gt kernel md文档 2

随机推荐

  • C++之socket.io编译使用

    文章目录 1 什么是socket io2 开发环境配置2 1 获取socket io的源码2 2 cmake安装2 3 boost安装2 3 1 获取源码2 3 2 解压编译下载 2 4 rapidjson下载2 5 websocketpp
  • github push的改版

    1 记录一次github 推送时的错误 错误如下 xff1a remote Please see https github blog 2020 12 15 token authentication requirements for git
  • Frp内网穿透

    Frp内网穿透 所有经过服务器的内网穿透都是有一个服务端和客户端 因为都需要借助服务器的公网ip来访问进而达到内网穿透的效果 frp的github开源地址 https github com fatedier frp frp的说明文档 htt
  • linux常见的几种排序方法

    我们以数组a 61 2 6 8 9 1 2 进行排序输出作为列子 xff1a 下面我来总结几种方法来帮助大家学习 1 xff1a 常规排序 首先2和6对比 xff0c 2不比6大不因此不交换 xff0c 所以还是268912 xff0c 然
  • 值得推荐的C/C++框架和库

    值得学习的C语言开源项目 Libevent libev是一个开源的事件驱动库 xff0c 基于epoll xff0c kqueue等OS提供的基础设施 其以高效出名 xff0c 它可以将IO事件 xff0c 定时器 xff0c 和信号统一起
  • cmake教程4(find_package使用)

    本文主要内容如下 xff1a 1 cmake find package的基本原理 2 如何编写自己的 cmake module模块 3 使用cmake find package 使用不同版本的opencv lib问题 xff08 openc
  • A*算法

    如此好贴 xff0c 不能不转 xff01 原文地址 xff1a http dev gameres com Program Abstract Arithmetic AmitAStar mht 本文版权归原作者 译者所有 xff0c 我只是转
  • 3.5RC_Channel 和 SRV_channel

    前言 这部分是之前在折腾ROVER的时候梳理了一遍 xff0c 但是没有形成记录 xff0c 现在从新从对象的角度来分析一遍 xff0c 包括映射 转换 数据结构 等方面进行梳理 xff1b 数据结构 首先分析的入口是从Rover read
  • CAN通信详解

    本章我们将向大家介绍如何使用STM32自带的CAN控制器来实现两个开发板之间的CAN通讯 xff0c 并将结果显示在TFTLCD模块上 本章分为如下几个部分 xff1a 30 1 CAN简介 30 2 硬件设计 30 3 软件设计 30 4
  • VC中出现的一些小问题的解决办法

    本人用的是vc6 0的 xff0c 在实际调试过程中出现一些小的问题 xff0c 通过网上查询资料得以解决 xff0c 特此在此整理下 xff0c 方便后者参考 第一问题 xff1a 程序源码编写完成后编译没有问题 xff0c 而链接时出现
  • C++编译报错`XXX‘被多次定义总结;未定义的引用等等

    1 C 43 43 编译报错 96 XXX 被多次定义总结 报错原因 xff1a 诸如类似的报错都是因为可能在两个或者多个 cpp文件 h文件定义该全局变量 xff0c 属于重复定义问题 解决办法是 xff1a 在VScode全局搜索该变量
  • C++必备万能头文件“#include<bits/stdc++.h>”

    c 43 43 代码一个简单的头文件 xff1a span class token macro property span class token directive hash span span class token directive
  • Livox SLAM(带LIO+闭环检测优化)

    主题 xff1a Livox雷达LIO 43 闭环检测优化 开源地址 xff1a LiDAR SLAM 该开源为 Livox雷达实现了一个一体化且即用型的 LiDAR 惯性里程计系统 前端基于基于开源里程计框架LIO Livox获取里程计信
  • 大疆livox定制的格式CustomMsg格式转换pointcloud2

    官方livox driver驱动livox雷达发出的点云topic有两种 xff0c 一种是大疆览沃定制的格式CustomMsg格式 xff0c 另一种是将CustomMsg格式 转换过的pointcloud2格式 xff0c 参见 Liv
  • paddlepaddle

    项目用到了paddlespeech2 xff0c 学了几天paddlepaddle xff0c 简单记录一下 文章目录 1 手写数字识别任务2 极简方案构建手写数字识别模型模型设计训练配置训练过程模型测试 3 手写数字识别 之数据处理4 手
  • SC-Lego-LOAM解析(上)

    文章目录 正文imageProjectionfeatureAssociationFeature Extraction 正文 SC Lego LOAM实际上应该并不对应某一篇特定的论文 xff0c 而是韩国KAIST在github开源的代码
  • SC-Lego-LOAM解析(中)

    上回说到经过连续帧间匹配 xff0c 激光odo给出来一个位姿估计 xff0c 但是是存在不断的误差的积累的 xff0c 需要与绝对的参考 xff08 地图 xff09 进行匹配 xff0c 以及进行回环检测和全局位姿优化 这也是正是map
  • SC-Lego-LOAM解析(下)

    回环检测是一个相对独立的模块 xff0c 这里再开一篇专门说明 前面两篇已经说过 xff0c 先对点云做了预处理 xff0c 然后进行连续帧之间的匹配即激光odom xff0c 然后是scan to map匹配 xff0c 并保存关键帧的位
  • Blog文章导航

    文章超链接 为了更快速的找到感兴趣的文章 xff0c 把我之前写的blog做一个简单的归类 xff1a 一 Nuttx相关 关于Nuttx的开发环境搭建类的文章 xff1a 1 genromfs 的使用及nuttx下romfs制作 2 nu
  • 关于计算程序耗时的几个方法

    1 一个来自r3live的timer tool工具 xff1a 一个功能丰富的头文件 34 tools timer hpp 34 span class token macro property span class token direct