changeset 5390:1c3b0cf341f0

Toolbox: added ElapsedTimeLogger debug tool
author Alain Mazy <am@osimis.io>
date Tue, 26 Sep 2023 12:28:13 +0200
parents 0e5e675b9750
children 8647020aa60a
files OrthancFramework/Sources/Toolbox.cpp OrthancFramework/Sources/Toolbox.h
diffstat 2 files changed, 51 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/OrthancFramework/Sources/Toolbox.cpp	Thu Sep 21 18:18:25 2023 +0200
+++ b/OrthancFramework/Sources/Toolbox.cpp	Tue Sep 26 12:28:13 2023 +0200
@@ -2513,6 +2513,36 @@
       value = value.substr(1, value.size() - 2);
     }
   }
+
+  Toolbox::ElapsedTimeLogger::ElapsedTimeLogger(const std::string& message)
+  : message_(message),
+    logged_(false)
+  {
+    Restart();
+  }
+
+  Toolbox::ElapsedTimeLogger::~ElapsedTimeLogger()
+  {
+    if (!logged_)
+    {
+      StopAndLog();
+    }
+  }
+
+  void Toolbox::ElapsedTimeLogger::Restart()
+  {
+    start_ = boost::posix_time::microsec_clock::universal_time();
+  }
+
+  void Toolbox::ElapsedTimeLogger::StopAndLog()
+  {
+    boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
+    boost::posix_time::time_duration diff = now - start_;
+    LOG(WARNING) << "ELAPSED TIMER: " << message_ << " (" << diff.total_microseconds() << " us)";
+    logged_ = true;
+  }
+
+
 }
 
 
--- a/OrthancFramework/Sources/Toolbox.h	Thu Sep 21 18:18:25 2023 +0200
+++ b/OrthancFramework/Sources/Toolbox.h	Tue Sep 26 12:28:13 2023 +0200
@@ -67,6 +67,8 @@
 #  include <pugixml.hpp>
 #endif
 
+#include <boost/date_time/posix_time/posix_time.hpp>
+
 
 namespace Orthanc
 {
@@ -373,6 +375,25 @@
                                 const Json::Value& source);
 
     static void RemoveSurroundingQuotes(std::string& value);
+
+    // This is a helper class to measure and log time spend e.g in a method.
+    // This should be used only during debugging and should likely not ever used in a release.
+    // By default, you should use it as a RAII but you may force Restart/StopAndLog manually if needed.
+    class ORTHANC_PUBLIC ElapsedTimeLogger
+    {
+    private:
+      const std::string         message_;
+      boost::posix_time::ptime  start_;
+      bool logged_;
+
+    public:
+      explicit ElapsedTimeLogger(const std::string& message);
+      ~ElapsedTimeLogger();  
+
+      void Restart();
+      void StopAndLog();
+    };
+
   };
 }