CDC Badge OS
Firmware for the CDC Badge v1.0 hardware security key
Loading...
Searching...
No Matches
CpuStats.cpp
Go to the documentation of this file.
1#include "cdc_core/CpuStats.h"
2#include "cdc_core/Raii.h"
3
4#include "freertos/FreeRTOS.h"
5#include "freertos/task.h"
6#include "esp_timer.h"
7
8#include <cstring>
9
10namespace cdc::core {
11
12bool CpuStats::sample(uint64_t& idleUs, uint64_t& wallUs)
13{
14#if (configGENERATE_RUN_TIME_STATS == 1) && (configUSE_TRACE_FACILITY == 1)
15 UBaseType_t count = uxTaskGetNumberOfTasks();
16 if (count == 0) return false;
17
18 auto buf = psramAlloc<TaskStatus_t>(count);
19 if (!buf) return false;
20
21 UBaseType_t got = uxTaskGetSystemState(buf.get(), count, nullptr);
22 uint64_t idle = 0;
23 for (UBaseType_t i = 0; i < got; ++i) {
24 // ESP-IDF SMP names the per-core idle tasks "IDLE0"/"IDLE1"; sum them.
25 if (buf[i].pcTaskName && std::strncmp(buf[i].pcTaskName, "IDLE", 4) == 0) {
26 idle += buf[i].ulRunTimeCounter;
27 }
28 }
29
30 idleUs = idle;
31 wallUs = static_cast<uint64_t>(esp_timer_get_time());
32 return true;
33#else
34 (void)idleUs;
35 (void)wallUs;
36 return false;
37#endif
38}
39
40uint8_t CpuStats::loadOverWindow(uint32_t windowMs)
41{
42 uint64_t idle0, wall0, idle1, wall1;
43 if (!sample(idle0, wall0)) return 0;
44 vTaskDelay(pdMS_TO_TICKS(windowMs));
45 if (!sample(idle1, wall1)) return 0;
46
47 uint64_t wallDelta = (wall1 - wall0) * static_cast<uint64_t>(configNUMBER_OF_CORES);
48 if (wallDelta == 0) return 0;
49 uint64_t idleDelta = idle1 - idle0;
50 if (idleDelta > wallDelta) idleDelta = wallDelta; // clamp counter-wrap glitch
51 return static_cast<uint8_t>(100 - (idleDelta * 100) / wallDelta);
52}
53
54} // namespace cdc::core
Shared RAII wrappers for firmware resources.
static uint8_t loadOverWindow(uint32_t windowMs=250)
Measure aggregate CPU load over a blocking window.
Definition CpuStats.cpp:40
static bool sample(uint64_t &idleUs, uint64_t &wallUs)
Snapshot cumulative idle CPU time and the wall-clock reference.
Definition CpuStats.cpp:12
PsramUniquePtr< T > psramAlloc(std::size_t count) noexcept
Allocate count elements of T in PSRAM (8-bit capable region).
Definition Raii.h:51