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

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值