rt-thread-official/examples/kernel/cpuusage.c

79 lines
1.6 KiB
C
Raw Normal View History

/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
*
*/
2013-01-08 22:40:58 +08:00
#include <rtthread.h>
#include <rthw.h>
2013-12-21 12:51:52 +08:00
#define CPU_USAGE_CALC_TICK 10
#define CPU_USAGE_LOOP 100
2013-01-08 22:40:58 +08:00
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()
{
rt_tick_t tick;
rt_uint32_t count;
volatile rt_uint32_t loop;
2013-01-08 22:40:58 +08:00
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();
}
2013-01-08 22:40:58 +08:00
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 ++;
}
2013-01-08 22:40:58 +08:00
/* 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;
2013-01-08 22:40:58 +08:00
/* no CPU usage */
cpu_usage_major = 0;
cpu_usage_minor = 0;
}
2013-01-08 22:40:58 +08:00
}
void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor)
{
RT_ASSERT(major != RT_NULL);
RT_ASSERT(minor != RT_NULL);
2013-01-08 22:40:58 +08:00
*major = cpu_usage_major;
*minor = cpu_usage_minor;
2013-01-08 22:40:58 +08:00
}
void cpu_usage_init()
{
/* set idle thread hook */
rt_thread_idle_sethook(cpu_usage_idle_hook);
2013-01-08 22:40:58 +08:00
}