119 lines
2.9 KiB
C++
119 lines
2.9 KiB
C++
#pragma once
|
|
|
|
#include <Arduino.h>
|
|
|
|
/**
|
|
* @brief CPU usage measurement utility for ESP32/ESP8266
|
|
*
|
|
* This class provides methods to measure CPU usage by tracking idle time
|
|
* and calculating the percentage of time the CPU is busy vs idle.
|
|
*/
|
|
class CpuUsage {
|
|
public:
|
|
/**
|
|
* @brief Construct a new CpuUsage object
|
|
*/
|
|
CpuUsage();
|
|
|
|
/**
|
|
* @brief Destructor
|
|
*/
|
|
~CpuUsage() = default;
|
|
|
|
/**
|
|
* @brief Initialize the CPU usage measurement
|
|
* Call this once during setup
|
|
*/
|
|
void begin();
|
|
|
|
/**
|
|
* @brief Start measuring CPU usage for the current cycle
|
|
* Call this at the beginning of your main loop
|
|
*/
|
|
void startMeasurement();
|
|
|
|
/**
|
|
* @brief End measuring CPU usage for the current cycle
|
|
* Call this at the end of your main loop
|
|
*/
|
|
void endMeasurement();
|
|
|
|
/**
|
|
* @brief Get the current CPU usage percentage
|
|
* @return float CPU usage percentage (0.0 to 100.0)
|
|
*/
|
|
float getCpuUsage() const;
|
|
|
|
/**
|
|
* @brief Get the average CPU usage over the measurement window
|
|
* @return float Average CPU usage percentage (0.0 to 100.0)
|
|
*/
|
|
float getAverageCpuUsage() const;
|
|
|
|
/**
|
|
* @brief Get the maximum CPU usage recorded
|
|
* @return float Maximum CPU usage percentage (0.0 to 100.0)
|
|
*/
|
|
float getMaxCpuUsage() const;
|
|
|
|
/**
|
|
* @brief Get the minimum CPU usage recorded
|
|
* @return float Minimum CPU usage percentage (0.0 to 100.0)
|
|
*/
|
|
float getMinCpuUsage() const;
|
|
|
|
/**
|
|
* @brief Reset all CPU usage statistics
|
|
*/
|
|
void reset();
|
|
|
|
/**
|
|
* @brief Check if measurement is currently active
|
|
* @return true if measurement is active, false otherwise
|
|
*/
|
|
bool isMeasuring() const;
|
|
|
|
/**
|
|
* @brief Get the number of measurements taken
|
|
* @return unsigned long Number of measurements
|
|
*/
|
|
unsigned long getMeasurementCount() const;
|
|
|
|
private:
|
|
// Measurement state
|
|
bool _initialized;
|
|
bool _measuring;
|
|
unsigned long _measurementCount;
|
|
|
|
// Timing variables
|
|
unsigned long _cycleStartTime;
|
|
unsigned long _idleStartTime;
|
|
unsigned long _totalIdleTime;
|
|
unsigned long _totalCycleTime;
|
|
|
|
// Statistics
|
|
float _currentCpuUsage;
|
|
float _averageCpuUsage;
|
|
float _maxCpuUsage;
|
|
float _minCpuUsage;
|
|
unsigned long _totalCpuTime;
|
|
|
|
// Rolling average window
|
|
static constexpr size_t ROLLING_WINDOW_SIZE = 10;
|
|
float _rollingWindow[ROLLING_WINDOW_SIZE];
|
|
size_t _rollingIndex;
|
|
bool _rollingWindowFull;
|
|
|
|
/**
|
|
* @brief Update rolling average calculation
|
|
* @param value New value to add to rolling average
|
|
*/
|
|
void updateRollingAverage(float value);
|
|
|
|
/**
|
|
* @brief Update min/max statistics
|
|
* @param value New value to check against min/max
|
|
*/
|
|
void updateMinMax(float value);
|
|
};
|