计算函数耗时

 

C++ 计算函数耗时的类。

在需要计算耗时的类里面,定义这个类的对象即可。

#ifndef  __ELAPSE_MILLSEC_H__
#define  __ELAPSE_MILLSEC_H__

//#include <iostream>  
#include <chrono>  
#include <iomanip> // 用于设置输出流的格式  
using namespace std;
//计算耗时
class ElapseMillsec{
public:

ElapseMillsec(std::string comment):m_comment(comment){
  m_Start = std::chrono::high_resolution_clock::now(); // 获取开始时间  
}

ElapseMillsec(){
  m_Start = std::chrono::high_resolution_clock::now(); // 获取开始时间  
}

~ElapseMillsec(){
  m_End = std::chrono::high_resolution_clock::now(); // 获取结束时间  
  // 计算持续时间  
  std::chrono::duration<double, std::milli> elapsed = m_End - m_Start;  
  // 输出执行时间,以毫秒为单位  
  printf("%s cost %f milliseconds.\r\n", m_comment.c_str(), elapsed.count());
}

private:
std::string m_comment="";
std::chrono::high_resolution_clock::time_point m_Start;
std::chrono::high_resolution_clock::time_point m_End;
};

#endif 

 

posted @ 2024-08-15 13:49  He_LiangLiang  阅读(1)  评论(0编辑  收藏  举报