Kaynağa Gözat

update timer

leon 4 hafta önce
ebeveyn
işleme
96729112f4
2 değiştirilmiş dosya ile 20 ekleme ve 17 silme
  1. 18 16
      src/common/utils.hpp
  2. 2 1
      src/nodes/base/base.cpp

+ 18 - 16
src/common/utils.hpp

@@ -27,26 +27,34 @@ static std::string str_format(const std::string &format, Args ... args)
 
 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();
+            stop_print();
         }
     }
 
-    // 可选:提供一个显式停止并打印的方法,如果需要在对象销毁前获取时间
-    void stopAndPrint() {
+    void print_time(const std::string& m_name, int64_t microseconds, double milliseconds, double seconds) {
+        int name_width = static_cast<int>(m_name.length() + 2);
+        int us_width = std::max(6 - name_width, 1);
+        int ms_width = std::max(8 - name_width, 1);
+        int s_width = std::max(10 - name_width, 1);
+    
+        printf("[%s] Elapsed time: %*lld us | %*.3f ms | %*.6f s\n",
+               m_name.c_str(),
+               us_width, static_cast<long long>(microseconds),
+               ms_width, milliseconds,
+               s_width, seconds);
+    }
+
+    void stop_print() {
         if (m_stopped) { // 如果已经停止并打印过,则直接返回
             return;
         }
@@ -61,17 +69,11 @@ public:
         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";
+        print_time(m_name, microseconds, milliseconds, seconds);
 
         m_stopped = true; // 标记为已停止并打印
     }
-
-    // 为了遵循 RAII 和防止意外行为,禁止拷贝和移动
+    
     Timer(const Timer&) = delete;
     Timer& operator=(const Timer&) = delete;
     Timer(Timer&&) = delete;

+ 2 - 1
src/nodes/base/base.cpp

@@ -1,4 +1,5 @@
 #include "common/meta.hpp"
+#include "common/utils.hpp"
 #include "nodes/base/base.hpp"
 
 namespace GNode
@@ -45,7 +46,7 @@ void BaseNode::work()
 {
     while (running_)
     {
-        // Timer timer("InferNode");
+        Timer timer(name_);
         bool has_data = false;
         for (auto& input_buffer : input_buffers_)
         {