Last active 4 hours ago

计算任务耗时, 单例类实现

Revision 2529cd5ae7dc6b8775d3ce3f7e1e5a5f3bad0dcf

stop_watch.h Raw
1
2#ifndef QTCONTROL_SRC_UTILS_STOPWATCH_H_
3#define QTCONTROL_SRC_UTILS_STOPWATCH_H_
4#include "chrono"
5
6class StopWatch {
7 public:
8 static StopWatch& GetInstance() {
9 static StopWatch instance;
10 return instance;
11 }
12 using Clock = std::chrono::high_resolution_clock;
13 /**
14 * @brief 开始计时, 所有时间从开始
15 */
16 void Start() {
17 if (!is_running_) {
18 start_time_ = Clock::now();
19 is_running_ = true;
20 }
21 }
22 /**
23 * @brief 暂时记时
24 */
25 void Stop() {
26 if (is_running_) {
27 auto end_time = Clock::now();
28 elapsed_time_ +=
29 std::chrono::duration<double>(end_time - start_time_).count();
30 is_running_ = false;
31 }
32 }
33
34 double ElapsedTimeS() const {
35 if (is_running_) {
36 auto current_time = Clock::now();
37 return elapsed_time_ +
38 std::chrono::duration<double>(current_time - start_time_).count();
39 }
40 return elapsed_time_;
41 }
42
43 double ElapsedTimeMs() const { return ElapsedTimeS() * 1000.0; }
44 double ElapsedTimeUs() const { return ElapsedTimeS() * 1e6; }
45 void Reset() {
46 elapsed_time_ = 0.0;
47 is_running_ = false;
48 }
49
50 StopWatch(const StopWatch&) = delete;
51 StopWatch& operator=(const StopWatch&) = delete;
52
53 private:
54 StopWatch() = default;
55 double elapsed_time_; /* 累积的时间,单位为秒 */
56 Clock::time_point start_time_;
57 bool is_running_;
58};
59#endif // QTCONTROL_SRC_UTILS_STOPWATCH_H_