平时经常需要对代码进行性能测试,自己用C++写了一个耗时统计组件,采用C++11标准,不依赖任何特定平台,包含文件即可使用。
// PerfTime.h
#ifndef _CPP_PERFTIME_H_
#define _CPP_PERFTIME_H_
namespace PerfTime {
// 耗时统计类型
enum class PerfType {
PERF_E2E = 0, // 端到端类型,支持多线程
PERF_ACC // 累加类型,支持多线程
};
void StartHit(PerfType type, const char *mark); // 开始打点
void EndHit(PerfType type, const char *mark); // 结束打点
void OutputReport(const char *file, bool isOutputCmd = true); // 输出报告
}
#endif // _CPP_PERFTIME_H_
// PerfTime.cpp
#include "PerfTime.h"
#include <string>
#include <vector>
#include <map>
#include <mutex>
#include <chrono>
#include <algorithm>
#include <numeric>
#include <fstream>
#include <sstream>
#include <iostream>
namespace PerfTime {
using UINT64 = unsigned long long;
//using namespace std::chrono;
// 打点类型
struct HitInfo {
PerfType type;
UINT64 timePoint;
bool isStart = true;
HitInfo(UINT64 tp, PerfType type, bool isStart) : timePoint(tp), type(type), isStart(isStart) {}
};
// 统计数据
struct StatisticsInfo {
UINT64 callCount;
UINT64 costTime;
StatisticsInfo(UINT64 call, UINT64 time) : callCount(call), costTime(time) {}
};
// 统计功能实现类
class Interface {
public:
static void StartHit(PerfType type, const std::string &am