diff OrthancServer/Sources/ServerContext.cpp @ 5346:566e8d32bd3a

Reduce the frequency of memory trimming from 100ms to 30s to avoid high idle CPU load
author Alain Mazy <am@osimis.io>
date Thu, 29 Jun 2023 09:43:20 +0200
parents b376abae664a
children 3c8286e5d07b aaf7c49a9ddc 16cbfefa15e9
line wrap: on
line diff
--- a/OrthancServer/Sources/ServerContext.cpp	Wed Jun 28 11:54:41 2023 +0200
+++ b/OrthancServer/Sources/ServerContext.cpp	Thu Jun 29 09:43:20 2023 +0200
@@ -110,16 +110,28 @@
 
 #if HAVE_MALLOC_TRIM == 1
   void ServerContext::MemoryTrimmingThread(ServerContext* that,
-                                           unsigned int sleepDelay)
+                                           unsigned int intervalInSeconds)
   {
+    boost::posix_time::ptime lastExecution = boost::posix_time::second_clock::universal_time();
+
     // This thread is started only if malloc_trim is defined
     while (!that->done_)
     {
-      boost::this_thread::sleep(boost::posix_time::milliseconds(sleepDelay));
-      
-      // If possible, gives memory back to the system 
-      // (see OrthancServer/Resources/ImplementationNotes/memory_consumption.txt)
-      malloc_trim(128*1024);
+      boost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();
+      boost::posix_time::time_duration elapsed = now - lastExecution;
+
+      if (elapsed.total_seconds() > intervalInSeconds)
+      {
+        // If possible, gives memory back to the system 
+        // (see OrthancServer/Resources/ImplementationNotes/memory_consumption.txt)
+        {
+          MetricsRegistry::Timer timer(that->GetMetricsRegistry(), "orthanc_memory_trimming_duration_ms");
+          malloc_trim(128*1024);
+        }
+        lastExecution = boost::posix_time::second_clock::universal_time();
+      }
+
+      boost::this_thread::sleep(boost::posix_time::milliseconds(100));
     }
   }
 #endif
@@ -439,7 +451,8 @@
       changeThread_ = boost::thread(ChangeThread, this, (unitTesting ? 20 : 100));
       
 #if HAVE_MALLOC_TRIM == 1
-      memoryTrimmingThread_ = boost::thread(MemoryTrimmingThread, this, 100);
+      LOG(INFO) << "Starting memory trimming thread at 30 seconds interval";
+      memoryTrimmingThread_ = boost::thread(MemoryTrimmingThread, this, 30);
 #else
       LOG(INFO) << "Your platform does not support malloc_trim(), not starting the memory trimming thread";
 #endif