线程分析器
公共头文件: #include "brookesia/lib_utils/thread_profiler.hpp"
概述
thread_profiler 提供线程(任务)运行状态与 CPU 使用情况的采样与统计能力, 便于分析系统负载与异常任务。
特性
采样任务状态、CPU 占用与栈等信息
支持周期性 profiling 与手动快照
提供排序、过滤与阈值检测能力
可与 TaskScheduler 联动进行定时采样
API 参考
Header File
Classes
-
class ThreadProfiler
FreeRTOS task profiler for CPU and stack usage monitoring.
This class provides a C++ interface to monitor FreeRTOS task CPU usage, stack usage, and other runtime statistics. It integrates naturally with TaskScheduler for periodic profiling.
Public Types
-
enum class TaskState
Task state mirrored from
FreeRTOSeTaskState.Values:
-
enumerator Running
eRunning.
-
enumerator Ready
eReady.
-
enumerator Blocked
eBlocked.
-
enumerator Suspended
eSuspended.
-
enumerator Deleted
eDeleted.
-
enumerator Invalid
eInvalid.
-
enumerator Running
-
enum class TaskStatus
Presence status of a task across two samples.
Values:
-
enumerator Normal
Task exists in both samples.
-
enumerator Created
Task appeared during the measurement window.
-
enumerator Deleted
Task disappeared during the measurement window.
-
enumerator Normal
-
enum class PrimarySortBy
Optional primary sort criterion.
Values:
-
enumerator None
Disable primary sorting.
-
enumerator CoreId
Sort by CPU core ID first.
-
enumerator None
-
enum class SecondarySortBy
Secondary sort criterion applied within the primary ordering.
Values:
-
enumerator CpuPercent
Sort by CPU usage percentage in descending order.
-
enumerator Priority
Sort by task priority in descending order.
-
enumerator StackUsage
Sort by stack high-water mark in ascending order.
-
enumerator Name
Sort by task name alphabetically.
-
enumerator CpuPercent
-
enum class ThresholdType
Metric used for threshold filtering and callbacks.
Values:
-
enumerator CpuPercent
Filter by CPU usage percentage.
-
enumerator Priority
Filter by task priority.
-
enumerator StackUsage
Filter by stack high-water mark.
-
enumerator CpuPercent
-
using ProfilingSignalSlot = std::function<void(const ProfileSnapshot&)>
Callback type accepted by
connect_profiling_signal().
-
using ThresholdSignalSlot = std::function<void(const std::vector<TaskInfo>&)>
Callback type accepted by
connect_threshold_signal().
-
using ProfilingSignal = boost::signals2::signal<void(const ProfileSnapshot&)>
Signal type emitted for each profiling snapshot.
-
using ThresholdSignal = boost::signals2::signal<void(const std::vector<TaskInfo>&)>
Signal type emitted when threshold matches are found.
-
using SignalConnection = boost::signals2::scoped_connection
Signal connection type.
备注
This is an RAII smart handle for managing the lifetime of callbacks. When this object is destroyed, the corresponding callback is automatically disconnected. It is recommended to use
std::move()to transfer ownership for manual management of the connection lifetime.
Public Functions
-
ThreadProfiler(const ThreadProfiler&) = delete
Copy construction is not supported.
-
ThreadProfiler &operator=(const ThreadProfiler&) = delete
Copy assignment is not supported.
-
ThreadProfiler(ThreadProfiler&&) = delete
Move construction is not supported.
-
ThreadProfiler &operator=(ThreadProfiler&&) = delete
Move assignment is not supported.
-
bool configure_profiling(const ProfilingConfig &config)
Update the profiling configuration.
- 参数
config – New profiler configuration.
- 返回
trueafter the configuration is stored.
-
ProfilingConfig get_profiling_config() const
Get the current profiling configuration.
- 返回
Active
ProfilingConfig.
Start periodic thread profiling using a task scheduler.
- 参数
scheduler – Scheduler used to run the two-stage sampling jobs. The caller must keep it alive until
stop_profiling()returns.sampling_duration_ms – Time between the first and second sample in milliseconds. Pass
0to useconfig.sampling_duration_ms.profiling_interval_ms – Period between profiling rounds in milliseconds. Pass
0to useconfig.profiling_interval_ms.
- 返回
trueon success, orfalseif profiling cannot be started.
-
void stop_profiling()
Stop periodic profiling.
-
void reset_profiling()
Reset captured data and registered callbacks without changing configuration.
-
inline bool is_profiling() const
Check whether periodic profiling is active.
- 返回
truewhen profiling tasks are active, orfalseotherwise.
-
inline std::shared_ptr<ProfileSnapshot> get_profiling_latest_snapshot()
Get the latest captured profiling snapshot.
- 返回
Shared pointer to the latest snapshot, or
nullptrif none is available.
-
SignalConnection connect_profiling_signal(ProfilingSignalSlot slot)
Subscribe to every generated profiling snapshot.
- 参数
slot – Callback invoked whenever a new snapshot is produced.
- 返回
RAII connection handle for the registered callback.
-
SignalConnection connect_threshold_signal(ThresholdType type, uint32_t threshold_value, ThresholdSignalSlot slot)
Subscribe to threshold matches for a specific metric.
- 参数
type – Metric to monitor.
threshold_value – Threshold value interpreted according to
type.slot – Callback invoked with the tasks that matched the threshold.
- 返回
RAII connection handle for the registered callback.
Public Static Functions
-
static inline ThreadProfiler &get_instance()
Get the process-wide singleton instance.
- 返回
Reference to the singleton profiler.
-
static std::shared_ptr<SampleResult> sample_tasks()
Capture a single raw scheduler sample.
- 返回
Shared pointer to the captured sample, or
nullptron failure.
-
static std::shared_ptr<ProfileSnapshot> take_snapshot(const SampleResult &start_result, const SampleResult &end_result)
Build a profiling snapshot from two raw samples.
- 参数
start_result – Sample taken at the beginning of the measurement window.
end_result – Sample taken at the end of the measurement window.
- 返回
Shared pointer to the computed snapshot, or
nullptron failure.
-
static void sort_tasks(std::vector<TaskInfo> &tasks, PrimarySortBy primary_sort = PrimarySortBy::CoreId, SecondarySortBy secondary_sort = SecondarySortBy::CpuPercent)
Sort task entries in place.
备注
The tasks will be sorted by the primary sort criteria first, then by the secondary sort criteria.
- 参数
tasks – Task vector to sort in place.
primary_sort – Optional primary sort criterion.
secondary_sort – Secondary sort criterion.
-
static void print_snapshot(const ProfileSnapshot &snapshot, PrimarySortBy primary_sort = PrimarySortBy::CoreId, SecondarySortBy secondary_sort = SecondarySortBy::CpuPercent)
Print a formatted snapshot table to the log.
- 参数
snapshot – Snapshot to print.
primary_sort – Primary sort criterion shown in the first sort column.
secondary_sort – Secondary sort criterion shown in the second sort column.
-
static bool get_task_by_name(const ProfileSnapshot &snapshot, const std::string &name, TaskInfo &task)
Find a task by name inside a snapshot.
- 参数
snapshot – Snapshot to search.
name – Task name to search for.
task – Output object that receives the matching task info.
- 返回
trueif a matching task is found, orfalseotherwise.
-
static std::vector<TaskInfo> get_tasks_above_threshold(const ProfileSnapshot &snapshot, ThresholdType type, uint32_t threshold_value)
Collect tasks whose metric meets a threshold.
备注
For CpuPercent: returns tasks with CPU >= threshold_value For Priority: returns tasks with priority >= threshold_value For StackUsage: returns tasks with stack HWM <= threshold_value (lower = more used)
- 参数
snapshot – Snapshot to inspect.
type – Threshold metric to apply.
threshold_value – Threshold value interpreted according to
type.
- 返回
Vector containing every task that satisfies the threshold.
-
struct ProfileSnapshot
Snapshot of all sampled task information.
-
struct ProfilingConfig
Configuration for periodic thread profiling.
Public Members
-
uint32_t sampling_duration_ms = 1000
Delay between the start and end sample, in milliseconds.
-
uint32_t profiling_interval_ms = 5000
Interval between profiling rounds, in milliseconds.
-
PrimarySortBy primary_sort = PrimarySortBy::CoreId
Primary sort criterion.
-
SecondarySortBy secondary_sort = SecondarySortBy::CpuPercent
Secondary sort criterion.
-
bool enable_auto_logging = true
Whether to log each generated snapshot automatically.
-
uint32_t sampling_duration_ms = 1000
-
struct SampleResult
Raw sample captured at a single instant.
-
struct Statistics
Aggregate statistics for a profiling snapshot.
Public Members
-
size_t total_tasks = 0
Total number of tasks in the snapshot.
-
size_t running_tasks = 0
Number of running tasks.
-
size_t blocked_tasks = 0
Number of blocked tasks.
-
size_t suspended_tasks = 0
Number of suspended tasks.
-
uint32_t total_cpu_percent = 0
Aggregate CPU usage percentage.
-
uint32_t sample_duration_ms = 0
Measurement window duration in milliseconds.
-
size_t total_tasks = 0
-
struct TaskInfo
Profile data for a single FreeRTOS task.
Public Members
-
std::string name
Task name.
-
TaskHandle_t handle = nullptr
FreeRTOS task handle.
-
uint32_t priority = 0
Current task priority.
-
BaseType_t core_id = -1
Bound CPU core ID, or
-1if unbound.
-
uint32_t stack_high_water_mark = 0
Stack high-water mark in bytes.
-
bool is_stack_external = false
Whether the stack is allocated in external RAM.
-
uint32_t runtime_counter = 0
Raw runtime counter captured in the ending sample.
-
uint32_t elapsed_time = 0
Runtime counter delta during the measurement window.
-
uint32_t cpu_percent = 0
CPU usage percentage over the measurement window.
-
TaskStatus status = TaskStatus::Normal
Presence status relative to the two samples.
-
std::string name
-
enum class TaskState