xref: /nrf52832-nimble/rt-thread/examples/kernel/cpuusage.c (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 #include <rtthread.h>
2 #include <rthw.h>
3 
4 #define CPU_USAGE_CALC_TICK    10
5 #define CPU_USAGE_LOOP        100
6 
7 static rt_uint8_t  cpu_usage_major = 0, cpu_usage_minor= 0;
8 static rt_uint32_t total_count = 0;
9 
10 static void cpu_usage_idle_hook()
11 {
12     rt_tick_t tick;
13     rt_uint32_t count;
14     volatile rt_uint32_t loop;
15 
16     if (total_count == 0)
17     {
18         /* get total count */
19         rt_enter_critical();
20         tick = rt_tick_get();
21         while(rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
22         {
23             total_count ++;
24             loop = 0;
25             while (loop < CPU_USAGE_LOOP) loop ++;
26         }
27         rt_exit_critical();
28     }
29 
30     count = 0;
31     /* get CPU usage */
32     tick = rt_tick_get();
33     while (rt_tick_get() - tick < CPU_USAGE_CALC_TICK)
34     {
35         count ++;
36         loop  = 0;
37         while (loop < CPU_USAGE_LOOP) loop ++;
38     }
39 
40     /* calculate major and minor */
41     if (count < total_count)
42     {
43         count = total_count - count;
44         cpu_usage_major = (count * 100) / total_count;
45         cpu_usage_minor = ((count * 100) % total_count) * 100 / total_count;
46     }
47     else
48     {
49         total_count = count;
50 
51         /* no CPU usage */
52         cpu_usage_major = 0;
53         cpu_usage_minor = 0;
54     }
55 }
56 
57 void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor)
58 {
59     RT_ASSERT(major != RT_NULL);
60     RT_ASSERT(minor != RT_NULL);
61 
62     *major = cpu_usage_major;
63     *minor = cpu_usage_minor;
64 }
65 
66 void cpu_usage_init()
67 {
68     /* set idle thread hook */
69     rt_thread_idle_sethook(cpu_usage_idle_hook);
70 }
71