cpuusage.c 1.5 KB
Newer Older
M
Ming, Bai 已提交
1 2 3
#include <rtthread.h>
#include <rthw.h>

G
Grissiom 已提交
4 5
#define CPU_USAGE_CALC_TICK    10
#define CPU_USAGE_LOOP        100
M
Ming, Bai 已提交
6 7 8 9 10 11

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()
{
G
Grissiom 已提交
12 13 14
    rt_tick_t tick;
    rt_uint32_t count;
    volatile rt_uint32_t loop;
M
Ming, Bai 已提交
15

G
Grissiom 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28
    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();
    }
M
Ming, Bai 已提交
29

G
Grissiom 已提交
30 31 32 33 34 35 36 37 38
    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 ++;
    }
M
Ming, Bai 已提交
39

G
Grissiom 已提交
40 41 42 43 44 45 46 47 48 49
    /* 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;
M
Ming, Bai 已提交
50

G
Grissiom 已提交
51 52 53 54
        /* no CPU usage */
        cpu_usage_major = 0;
        cpu_usage_minor = 0;
    }
M
Ming, Bai 已提交
55 56 57 58
}

void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor)
{
G
Grissiom 已提交
59 60
    RT_ASSERT(major != RT_NULL);
    RT_ASSERT(minor != RT_NULL);
M
Ming, Bai 已提交
61

G
Grissiom 已提交
62 63
    *major = cpu_usage_major;
    *minor = cpu_usage_minor;
M
Ming, Bai 已提交
64 65 66 67
}

void cpu_usage_init()
{
G
Grissiom 已提交
68 69
    /* set idle thread hook */
    rt_thread_idle_sethook(cpu_usage_idle_hook);
M
Ming, Bai 已提交
70
}