* @brief Get thread usage percentage relative to total system CPU time * * This function calculates the CPU usage percentage of a specific thread * relative to the total CPU time consumed by all threads in the system. * * @param thread Pointer to the thread object. Must not be NULL. * * @return The CPU usage percentage as an integer value (0-100). * Returns 0 if total system time i
| 554 | * @note If thread is NULL, an assertion will be triggered in debug builds. |
| 555 | */ |
| 556 | rt_uint8_t rt_thread_get_usage(rt_thread_t thread) |
| 557 | { |
| 558 | rt_ubase_t thread_time; |
| 559 | rt_ubase_t total_time = 0U; |
| 560 | int i; |
| 561 | rt_cpu_t pcpu; |
| 562 | |
| 563 | RT_ASSERT(thread != RT_NULL); |
| 564 | |
| 565 | thread_time = thread->user_time + thread->system_time; |
| 566 | |
| 567 | /* Calculate total system time by summing all CPUs' time */ |
| 568 | for (i = 0; i < RT_CPUS_NR; i++) |
| 569 | { |
| 570 | pcpu = rt_cpu_index(i); |
| 571 | total_time += pcpu->cpu_stat.user + pcpu->cpu_stat.system + pcpu->cpu_stat.idle; |
| 572 | } |
| 573 | |
| 574 | if (total_time > 0U) |
| 575 | { |
| 576 | /* Calculate thread usage percentage: (thread_time * 100) / total_time */ |
| 577 | rt_ubase_t usage = (thread_time * 100U) / total_time; |
| 578 | return (rt_uint8_t)(usage > 100U ? 100U : usage); |
| 579 | } |
| 580 | |
| 581 | return 0U; |
| 582 | } |
| 583 | #endif /* RT_USING_CPU_USAGE_TRACER */ |
| 584 | |
| 585 | #if defined(RT_USING_LIBC) && defined(RT_USING_FINSH) |
no test coverage detected