CPU 的使用率一般是我們比較關心的問題,在這里我們就用空閑線程的鈎子函數去統計 CPU 的使用率,並通過串口打印出來。
首先我們在初始化線程中設置好鈎子函數,並在 LED 線程中給系統人為的加入很多“事情”,讓其占用率變高,方便統計,然后每個 1 秒中打印一次 CPU 使用率。其中 CPU 的使用率我們是根據 CPU 的空閑率反推出來的。
#include <rtthread.h> #include <rthw.h> #define CPU_USAGE_CALC_TICK 10 #define CPU_USAGE_LOOP 100 static rt_uint8_t cpu_usage_major = 0, cpu_usage_minor= 0; static rt_uint32_t total_count = 0; static void cpu_usage_idle_hook(void) { rt_tick_t tick; rt_uint32_t count; volatile rt_uint32_t loop; if (total_count == 0) { /* get total count */ rt_enter_critical(); tick = rt_tick_get(); while(rt_tick_get() - tick < CPU_USAGE_CALC_TICK) { total_count ++; loop = 0; while (loop < CPU_USAGE_LOOP) loop ++; } rt_exit_critical(); } count = 0; /* get CPU usage */ tick = rt_tick_get(); while (rt_tick_get() - tick < CPU_USAGE_CALC_TICK) { count ++; loop = 0; while (loop < CPU_USAGE_LOOP) loop ++; } /* calculate major and minor */ if (count < total_count) { count = total_count - count; cpu_usage_major = (count * 100) / total_count; cpu_usage_minor = ((count * 100) % total_count) * 100 / total_count; } else { total_count = count; /* no CPU usage */ cpu_usage_major = 0; cpu_usage_minor = 0; } } void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor) { RT_ASSERT(major != RT_NULL); RT_ASSERT(minor != RT_NULL); *major = cpu_usage_major; *minor = cpu_usage_minor; } void cpu_usage_init(void) { /* set idle thread hook */ rt_thread_idle_sethook(cpu_usage_idle_hook); }
前面說過,系統的心跳時鍾過快,會增加 cpu 的負擔,我們可以在這里來驗證,讀者可
以將系統滴答時間改為 1ms,然后你將會發現 cpu 的使用率從 24%升高到了 87%!!,如下圖: