C++实现系统性能检测工具

本文介绍了一款用于实时检测系统性能的开源工具,通过修改实现了代码耗时和FPS的统计功能。工具提供了创建作用域来跟踪特定代码段的执行时间,并支持自定义输出间隔。在主函数中展示了如何在多线程环境中使用该工具进行性能监控。

最近在项目中需要一个小工具来实时检测系统性能,检测某一块代码耗时多长时间,然后我在网上找了一个开源的项目稍作修改实现了这个功能。下面把代码贴出来给大家使用。
profiler.h 文件

#ifndef HOBOTXSTREAM_PROFILER_H_
#define HOBOTXSTREAM_PROFILER_H_

#include <iostream>
#include <atomic>
#include <chrono>
#include <fstream>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#define LOG_TAG "ppp-ppp"
#include <log/log.h>

inline std::int64_t getMicroSecond() {
  auto time_now = std::chrono::system_clock::now();
  auto duration_in_ms = std::chrono::duration_cast<std::chrono::microseconds>(
      time_now.time_since_epoch());
  return duration_in_ms.count();
}

struct FpsStatisticInfo {
  /// the interval of Statistical result output
  static int cycle_ms;
  /// FPS start time
  std::int64_t pre_time;
  /// current total count
  std::atomic_int cnt;

  FpsStatisticInfo() { cnt = 0; }
};

struct TimeStatisticInfo {
  /// the interval of Statistical result output
  static int cycle_ms;
  /// process start time
  std::int64_t pre_time;

  TimeStatisticInfo() { pre_time = 0; }
};

#if 0
struct StatisticInfo {
  /// the interval of Statistical result output
  static int cycle_num;
  /// the interval of Statistical result output
  static int cycle_ms;

  /// start time
  int64_t pre_time;
  /// current total count
  std::atomic_int cnt;

  StatisticInfo() {
    cnt = 0;
    // pre_time = getMicroSecond();
  }
};
#endif

class ProfilerScope;
class Profiler;
typedef std::shared_ptr<Profiler> ProfilerPtr;

class Profiler : public std::enable_shared_from_this<Profiler> {
 public:
  Profiler() = default;
  ~Profiler();

  enum class State { kNotRunning = 0, kRunning };

  static ProfilerPtr Get();
  static ProfilerPtr Release() {
    if (instance_) {
      instance_ = nullptr;
    }
    return instance_;
  }

  inline bool IsRunning() const { return state_ == State::kRunning; }

  void Log(const std::stringstream &ss);
  void Write_Log();
  inline void Start() { SetState(State::kRunning); }
  inline void Stop() { SetState(State::kNotRunning); }

  bool SetOutputFile(const std::string &file);

  void SetIntervalForTimeStat(int cycle_ms);
  void SetIntervalForFPSStat(int cycle_ms);

  enum class Type { kFps, kProcessTime };
  std::unique_ptr<ProfilerScope> CreateScope(const std::string &name,
                                             const std::string &tag);

  std::string name_ = "";

 private:
  Profiler(const Profiler &) = delete;
  void SetState(Profiler::State state);
  State state_ = State::kNotRunning;
  static ProfilerPtr instance_;
  std::unordered_map<std::string, std::shared_ptr<FpsStatisticInfo>> fps_stats_;
  std::unordered_map<std::string, std::shared_ptr<TimeStatisticInfo>>
      time_stats_;

  std::fstream foi_;
  std::mutex lock_;
};

class ProfilerScope {
 public:
  ProfilerScope(ProfilerPtr profiler, const std::string &name,
                const std::string tag)
      : profiler_(profiler), name_(name), tag_(tag) {}

  virtual ~ProfilerScope() {}

 protected:
  ProfilerPtr profiler_;
  std::string name_;
  std::string tag_;
};

class ScopeTime : public ProfilerScope {
 public:
  ScopeTime(ProfilerPtr profiler, const std::string &name,
            const std::string tag, std::shared_ptr<TimeStatisticInfo> stat)
      : ProfilerScope(profiler, name, tag), stat_(stat) {
    if (stat_->pre_time == 0) {
      stat_->pre_time = getMicroSecond();
    }
  }

  ~ScopeTime() {
    auto cur_time = getMicroSecond();
    auto diff = cur_time - stat_->pre_time;
    if (diff > stat_->cycle_ms) {
      std::stringstream ss;
      ss << name_ << " | " << std::this_thread::get_id() << " | "
         << "X"
         << " | " << std::to_string(stat_->pre_time) << " | "
         << std::to_string(diff) << "\n";
      profiler_->Log(ss);
    }
    stat_->pre_time = 0;
  }

 private:
  std::shared_ptr<TimeStatisticInfo> stat_;
};

class ScopeFps : public ProfilerScope {
 public:
  ScopeFps(ProfilerPtr profiler, const std::string &name, const std::string tag,
           std::shared_ptr<FpsStatisticInfo> stat)
      : ProfilerScope(profiler, name, tag), stat_(stat) {
    if (stat_->cnt == 0) {
      stat_->pre_time = getMicroSecond();
    }
    stat_->cnt++;
  }

  ~ScopeFps() {
    auto cur_time = getMicroSecond();
    auto diff = cur_time - stat_->pre_time;
    if (diff > stat_->cycle_ms) {
      std::stringstream ss;
      ss << name_ << " | " << std::this_thread::get_id() << " | "
         << "C"
         << " | " << std::to_string(stat_->pre_time) << " | "
         << stat_->cnt / (diff / 1000.0 / 1000) << "\n";
      ss << name_ << " | " << std::this_thread::get_id() << " | "
         << "C"
         << " | " << std::to_string(cur_time) << " | "
         << "0"
         << "\n";
      profiler_->Log(ss);
      stat_->cnt = 0;
    }
  }

 private:
  std::shared_ptr<FpsStatisticInfo> stat_;
};

#define RUN_FPS_PROFILER_WITH_PROFILER(profiler, name) \
  std::unique_ptr<ProfilerScope> scope_fps;            \
  if (profiler->IsRunning()) {                         \
    scope_fps = profiler->CreateScope(name, "FPS");    \
  }

#define RUN_TIME_PROFILER_WITH_PROFILER(profiler, name) \
  std::unique_ptr<ProfilerScope> scope_time;		\
  if (profiler->IsRunning()) { 				\
    scope_time = profiler->CreateScope(name, "TIME");	\
  }
#define RUN_PROCESS_TIME_PROFILER(name)		\
  RUN_TIME_PROFILER_WITH_PROFILER(Profiler::Get(), name);


#define RUN_FPS_PROFILER(name) \
  RUN_FPS_PROFILER_WITH_PROFILER(Profiler::Get(), name)


#define STOP_TIME_PROFILER_WITH_PROFILER(profiler) \
  profiler->Write_Log();

#define STOP_PROCESS_TIME_PROFILER \
	STOP_TIME_PROFILER_WITH_PROFILER(Profiler::Get()); 
// TODO(zhe.sun) SnapshotMethod

#endif  // HOBOTXSTREAM_PROFILER_H_

profiler.c 文件

#include "profiler.h"

#include <errno.h>
#include <string.h>

#include <iostream>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include "config.h"
#include "json_features.h"
#include "reader.h"
#include "value.h"
#include "writer.h"
#ifdef __cplusplus
extern "C" {
#endif
#define LOG_TAG "profiler"
#include <log/log.h>
#include<pthread.h>
#ifdef __cplusplus
}
#endif

#define PROFILER_METHOD "log.txt"
namespace hobotprofiler {
static std::vector<std::string> split(const std::string &str, char delim) {
  std::vector<std::string> elems;
  std::istringstream iss(str);
  for (std::string item; getline(iss, item, delim);)
    if (item.empty()) {
      continue;
    } else {
      item.erase(0, item.find_first_not_of(" "));
      item.erase(item.find_last_not_of(" ") + 1);
      elems.push_back(item);
    }
  return elems;
}
}  // namespace hobotprofiler

int TimeStatisticInfo::cycle_ms = 10;

int FpsStatisticInfo::cycle_ms = 200 * 1000;
/// used to guarantee the Profiler::instance_ is created only once

std::once_flag create_profiler_flag;
ProfilerPtr Profiler::instance_;
ProfilerPtr Profiler::Get() {
  if (!instance_) {
    std::call_once(create_profiler_flag, []() {
      instance_ = ProfilerPtr(new Profiler());
      instance_->SetOutputFile(PROFILER_METHOD);
      instance_->SetState(State::kRunning);
    });
  }
  return instance_;
}

Profiler::~Profiler() {
  if (foi_.is_open()) {
    foi_.close();
  }
  //LOGD << "~Profiler() End";
}

void Profiler::Log(const std::stringstream &ss) {
  // TODO(SONGSHAN.GONG): fstream or iostream may not thread-safe,
  // need replace as an thread-safe logging system.
  std::lock_guard<std::mutex> lock(lock_);
  if (foi_.is_open()) {
    foi_ << ss.str();
  } else {
      foi_.open(PROFILER_METHOD, std::fstream::out | std::fstream::in | std::fstream::binary |
                      std::fstream::trunc);
      if (foi_.fail()) {
       
      } else {
	foi_ << ss.str();
      }
    }
}

void Profiler::Write_Log()
{
 std::cout << "~Profiler() Start";
  std::lock_guard<std::mutex> lock(lock_);

  Json::Value array_config;

  if (!foi_.is_open()) {
    std::cout << "~Profiler() End";
    return;
  }
  std::string line;
  foi_.seekg(std::ios::beg);  // 从头开始读取

  while (getline(foi_, line)) {  // line中不包括每行的换行符
    std::vector<std::string> elements = hobotprofiler::split(line, '|');
    if (elements.size() != 5) {
     
      continue;
    }

    Json::Value item;
    item["pid"] = "0";
    item["name"] = elements[0];
    item["tid"] = elements[1];
    item["ph"] = elements[2];
    item["ts"] = elements[3];
    // 判断是哪种类型
    if (elements[2] == "X") {
      item["dur"] = elements[4];
      array_config.append(item);
    } else if (elements[2] == "C") {
      Json::Value args;
      args["frame cnt"] = elements[4];
      item["args"] = args;
      array_config.append(item);
    }
  }

  foi_.clear();               // 从头开始写入
  foi_.seekg(std::ios::beg);  // 从头开始写入
  foi_ << array_config.toStyledString();
  if (foi_.is_open()) {
    foi_.close();
  }
}

void Profiler::SetState(Profiler::State state) {
  std::lock_guard<std::mutex> lock(lock_);
  if (state != state_) {
    state_ = state;
    //
    for (auto &stat : fps_stats_) {
      stat.second->cnt = 0;
    }
    for (auto &stat : time_stats_) {
      stat.second->pre_time = 0;
    }
  }
}

bool Profiler::SetOutputFile(const std::string &file) {
  std::lock_guard<std::mutex> lock(lock_);
  if (foi_.is_open()) {
    foi_.close();
  }
  foi_.open(file, std::fstream::out | std::fstream::in | std::fstream::binary |
                      std::fstream::trunc);
  if (foi_.fail()) {
    std::cout << "Failed to open " << file << ", error msg is " << strerror(errno);
    return false;
  }
  foi_.seekg(0, std::ios::beg);  // 从头开始写入
  return true;
}

void Profiler::SetIntervalForTimeStat(int cycle_ms) {
  //HOBOT_CHECK_GE(cycle_ms, 1);
  TimeStatisticInfo::cycle_ms = cycle_ms;
  std::cout << "SetFrameIntervalForTimeStat to " << cycle_ms;
}

void Profiler::SetIntervalForFPSStat(int cycle_ms) {
  //HOBOT_CHECK_GE(cycle_ms, 1);
  FpsStatisticInfo::cycle_ms = cycle_ms;
  std::cout << "SetTimeIntervalForFPSStat to " << cycle_ms;
}

std::unique_ptr<ProfilerScope> Profiler::CreateScope(const std::string &name,
                                                     const std::string &tag) {
  std::lock_guard<std::mutex> lock(lock_);
  auto id = std::this_thread::get_id();
  std::stringstream ss;
  ss << id;
  std::string thread_id = name + "_" + ss.str();
//  SetIntervalForTimeStat(3000);
  if (tag == "FPS") {
    std::shared_ptr<FpsStatisticInfo> curr_stat;
    if (fps_stats_.find(thread_id) == fps_stats_.end()) {
      fps_stats_[thread_id] = std::make_shared<FpsStatisticInfo>();
    }
    curr_stat = fps_stats_[thread_id];
    std::unique_ptr<ProfilerScope> scope(
        new ScopeFps(shared_from_this(), name, tag, curr_stat));
    return scope;
  } else if (tag == "TIME") {
    std::shared_ptr<TimeStatisticInfo> curr_stat;
    if (time_stats_.find(thread_id) == time_stats_.end()) {
      time_stats_[thread_id] = std::make_shared<TimeStatisticInfo>();
    }
    curr_stat = time_stats_[thread_id];
    std::unique_ptr<ProfilerScope> scope(
        new ScopeTime(shared_from_this(), name, tag, curr_stat));
    return scope;
  }
  //HOBOT_CHECK(false) << "Not support scope: " << tag;
  return nullptr;
}

主函数调用

#include <thread>
#include <iostream>
#include <unistd.h>
#include "profiler.h"

using namespace std;

void proc(int x)
{
	RUN_PROCESS_TIME_PROFILER("test")
	usleep(3000);
	STOP_TIME_PROFILER_WITH_PROFILER
}

int main()
{
	int x = 10;
	std:thread th1(proc, x);
	th1.join();
	std:thread th2(proc, x);
	th2.join();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值