|
@@ -18,4 +18,69 @@ static std::string str_format(const std::string &format, Args ... args)
|
|
|
return std::string(buf.get(), buf.get() + size_buf - 1);
|
|
|
}
|
|
|
|
|
|
+#pragma once // 或者使用传统的 include guards
|
|
|
+
|
|
|
+#include <chrono> // 用于时间测量
|
|
|
+#include <iostream> // 用于打印输出
|
|
|
+#include <string> // 用于计时器名称
|
|
|
+#include <iomanip> // 用于格式化输出 (std::fixed, std::setprecision)
|
|
|
+
|
|
|
+class Timer {
|
|
|
+public:
|
|
|
+ // 构造函数:记录开始时间,并可选地接收一个名称
|
|
|
+ Timer(const std::string& name = "Timer")
|
|
|
+ : m_name(name),
|
|
|
+ m_startTimePoint(std::chrono::high_resolution_clock::now()),
|
|
|
+ m_stopped(false) // 初始化为未停止状态
|
|
|
+ {
|
|
|
+ // 可以选择在这里打印开始信息,但通常只在结束时打印
|
|
|
+ // std::cout << "[" << m_name << "] Timer started...\n";
|
|
|
+ }
|
|
|
+
|
|
|
+ // 析构函数:计算并打印耗时
|
|
|
+ ~Timer() {
|
|
|
+ // 确保只打印一次,即使 stop() 被显式调用过
|
|
|
+ if (!m_stopped) {
|
|
|
+ stopAndPrint();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 可选:提供一个显式停止并打印的方法,如果需要在对象销毁前获取时间
|
|
|
+ void stopAndPrint() {
|
|
|
+ if (m_stopped) { // 如果已经停止并打印过,则直接返回
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ auto endTimePoint = std::chrono::high_resolution_clock::now();
|
|
|
+
|
|
|
+ // 计算持续时间
|
|
|
+ auto duration = endTimePoint - m_startTimePoint;
|
|
|
+
|
|
|
+ // 将持续时间转换为更易读的单位(例如:微秒、毫秒、秒)
|
|
|
+ long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
|
|
|
+ double milliseconds = microseconds / 1000.0;
|
|
|
+ double seconds = milliseconds / 1000.0;
|
|
|
+
|
|
|
+ // 打印结果
|
|
|
+ std::cout << "[" << m_name << "] Elapsed time: "
|
|
|
+ << microseconds << " us | "
|
|
|
+ // 使用 iomanip 设置精度,使输出更整齐
|
|
|
+ << std::fixed << std::setprecision(3) << milliseconds << " ms | "
|
|
|
+ << std::fixed << std::setprecision(6) << seconds << " s\n";
|
|
|
+
|
|
|
+ m_stopped = true; // 标记为已停止并打印
|
|
|
+ }
|
|
|
+
|
|
|
+ // 为了遵循 RAII 和防止意外行为,禁止拷贝和移动
|
|
|
+ Timer(const Timer&) = delete;
|
|
|
+ Timer& operator=(const Timer&) = delete;
|
|
|
+ Timer(Timer&&) = delete;
|
|
|
+ Timer& operator=(Timer&&) = delete;
|
|
|
+
|
|
|
+private:
|
|
|
+ std::string m_name; // 计时器名称
|
|
|
+ std::chrono::time_point<std::chrono::high_resolution_clock> m_startTimePoint; // 开始时间点
|
|
|
+ bool m_stopped; // 标记是否已手动停止并打印
|
|
|
+};
|
|
|
+
|
|
|
#endif
|