最後活躍 4 hours ago

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

nichijou 已修改 4 hours ago. 還原成這個修訂版本

1 file changed, 15 insertions, 1 deletion

stop_watch.h

@@ -56,4 +56,18 @@ class StopWatch {
56 56 Clock::time_point start_time_;
57 57 bool is_running_;
58 58 };
59 - #endif // QTCONTROL_SRC_UTILS_STOPWATCH_H_
59 + #endif // QTCONTROL_SRC_UTILS_STOPWATCH_H_
60 +
61 + // main.cpp使用
62 + auto& stop_watch = StopWatch::GetInstance();
63 + /* 需要测试的代码段开始 */
64 + stop_watch.Start();
65 + float qd[2];
66 + float torque[2];
67 + float current[8];
68 + const int test_times = 30000;
69 + for (int i = 0; i < test_times; ++i) {
70 + MotorCurrentInverse(qd, torque, current);
71 + }
72 + /* 需要测试的代码段结束 */
73 + qDebug() << "MotorCurrentInverse avg_run time" << stop_watch.ElapsedTimeUs() / test_times << "us";

nichijou 已修改 4 hours ago. 還原成這個修訂版本

1 file changed, 59 insertions

stop_watch.h(檔案已創建)

@@ -0,0 +1,59 @@
1 +
2 + #ifndef QTCONTROL_SRC_UTILS_STOPWATCH_H_
3 + #define QTCONTROL_SRC_UTILS_STOPWATCH_H_
4 + #include "chrono"
5 +
6 + class 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_
上一頁 下一頁