From 093a30acdb8e0b1248af086c86b1f427e4d91acc Mon Sep 17 00:00:00 2001
From: Daniele Cattaneo <daniele3.cattaneo@mail.polimi.it>
Date: Tue, 4 Apr 2023 22:30:24 +0200
Subject: [PATCH] Add a method in CPUTimeCounter to get the current CPU time
 consumed by a thread.

Useful for timing functions when other threads are simultaneously in execution.

Signed-off-by: Terraneo Federico <fede.tft@miosix.org>
---
 miosix/kernel/cpu_time_counter.cpp | 13 +++++++++++++
 miosix/kernel/cpu_time_counter.h   |  6 ++++++
 2 files changed, 19 insertions(+)

diff --git a/miosix/kernel/cpu_time_counter.cpp b/miosix/kernel/cpu_time_counter.cpp
index ea57ed48..854a3507 100644
--- a/miosix/kernel/cpu_time_counter.cpp
+++ b/miosix/kernel/cpu_time_counter.cpp
@@ -26,6 +26,7 @@
  ***************************************************************************/
 
 #include "cpu_time_counter.h"
+#include "cpu_time_counter_private.h"
 #include "kernel/kernel.h"
 
 #ifdef WITH_CPU_TIME_COUNTER
@@ -36,6 +37,18 @@ Thread *CPUTimeCounter::head = nullptr;
 Thread *CPUTimeCounter::tail = nullptr;
 volatile unsigned int CPUTimeCounter::nThreads = 0;
 
+long long CPUTimeCounter::getActiveThreadTime()
+{
+    long long curTime, usedTime, lastAct;
+    {
+        PauseKernelLock pk;
+        curTime = IRQgetTime();
+        usedTime = runningThread->timeCounterData.usedCpuTime;
+        lastAct = runningThread->timeCounterData.lastActivation;
+    }
+    return usedTime + (curTime - lastAct);
+}
+
 void CPUTimeCounter::PKremoveDeadThreads()
 {
     Thread *prev = nullptr;
diff --git a/miosix/kernel/cpu_time_counter.h b/miosix/kernel/cpu_time_counter.h
index d9e0f998..6e05ea08 100644
--- a/miosix/kernel/cpu_time_counter.h
+++ b/miosix/kernel/cpu_time_counter.h
@@ -148,6 +148,12 @@ public:
         return iterator(nullptr);
     }
 
+    /**
+     * \returns the amount of CPU run-time consumed up to now by the currently
+     * active thread.
+     */
+    static long long getActiveThreadTime();
+
 private:
     // The following methods are called from basic_scheduler to notify
     // CPUTimeCounter of various events.
-- 
GitLab