#ifndef QTCONTROL_SRC_UTILS_STOPWATCH_H_ #define QTCONTROL_SRC_UTILS_STOPWATCH_H_ #include "chrono" class StopWatch { public: static StopWatch& GetInstance() { static StopWatch instance; return instance; } using Clock = std::chrono::high_resolution_clock; /** * @brief 开始计时, 所有时间从开始 */ void Start() { if (!is_running_) { start_time_ = Clock::now(); is_running_ = true; } } /** * @brief 暂时记时 */ void Stop() { if (is_running_) { auto end_time = Clock::now(); elapsed_time_ += std::chrono::duration(end_time - start_time_).count(); is_running_ = false; } } double ElapsedTimeS() const { if (is_running_) { auto current_time = Clock::now(); return elapsed_time_ + std::chrono::duration(current_time - start_time_).count(); } return elapsed_time_; } double ElapsedTimeMs() const { return ElapsedTimeS() * 1000.0; } double ElapsedTimeUs() const { return ElapsedTimeS() * 1e6; } void Reset() { elapsed_time_ = 0.0; is_running_ = false; } StopWatch(const StopWatch&) = delete; StopWatch& operator=(const StopWatch&) = delete; private: StopWatch() = default; double elapsed_time_; /* 累积的时间,单位为秒 */ Clock::time_point start_time_; bool is_running_; }; #endif // QTCONTROL_SRC_UTILS_STOPWATCH_H_