定义一个C++的类,析构的时候输出当前函数执行耗时

背景介绍:
有时候我们需要知道一个函数的执行耗时。

按照传统方法,至少要定义一个 start, end, 然后计算差值,输出差值,4个步骤。

这里,我们定义一个  ElapseMillsec 类,然后在类的生命周期结束的时候,在析构函数里面 计算出差值。

此时   ElapseMillsec 类 的生命周期,就是函数执行耗时时间。

 

使用方法:

  使用的时候,我们只需要在需要计算执行耗时的函数的最开头,定义一个 

   ElapseMillsec oneCost("test_add");  

类似这样的对象即可。 参数是我们需要添加的个性化注释内容。

 

#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;  
  // 输出执行时间,以毫秒为单位  
  std::cout << m_comment <<" cost " << elapsed.count() << " milliseconds." << std::endl;  
}

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

int main(){
  long long sum = 0; // 用于累加,但结果并不重要  
  ElapseMillsec oneCost("test_add");
  // 从1加到100万  
  for (int i = 1; i <= 1000000; ++i) {  
      sum += i; // 自加操作  
  }  
  std::cout<<"Hello emsdk!"<<std::endl;
  return 0;
}


// step1: 编译C++工程
// emcc ./input/hello1.cpp -o ./output/hello1/hello1.html

// step2: 运行web
// emrun --no_browser  --port 8081  ./output/hello1/

// step3: 浏览器查看
// localhost:8081/hello1.html




  
   

 

posted @ 2024-08-06 10:42  He_LiangLiang  阅读(1)  评论(0编辑  收藏  举报