A CPU usage measurement method based on FreeRTOS and its principle introduction

Publisher:码上奇迹Latest update time:2016-09-02 Source: eefocusKeywords:FreeRTOS Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
1 Introduction

For performance reasons, sometimes we want to know the CPU usage rate, so as to determine the CPU load and whether it is "capable" enough for the current operating environment. This article will introduce a method for calculating CPU occupancy and its implementation principle.


2. Transplantation Algorithm
2.1 Algorithm Introduction
This algorithm is based on the operating system. In theory, it is not limited to any operating system, as long as there is task scheduling. This article will take FreeRTOST as an example to introduce the use of this algorithm.

The algorithm introduced in this article comes from the Cube library. Its location in the Cube library is shown in the figure below:

1

This article will take STM32F4 as an example, and the test environment is the STM3240G-EVAL evaluation board.

2.2. Start porting
This article takes the sample code project STM32Cube_FW_F4_V1.10.0\Projects\STM324xG_EVAL\Applications\FreeRTOS\FreeRTOS_ThreadCreation in CubeF4 as an example, and uses IAR as the IDE.

Step 1:
Use IAR to open the FreeRTOS_ThreadCreation project, add the cpu_utils.c file to the project, and add the corresponding header file directory to the project:

2

Step 2: Open the FreeRTOST configuration header file FreeRTOSConfig.h and modify the values ​​of the macros configUSE_IDLE_HOOK and configUSE_TICK_HOOK to 1:

#defineconfigUSE_PREEMPTION 1
#defineconfigUSE_IDLE_HOOK 1 //Modify the value of this macro to 1
#defineconfigUSE_TICK_HOOK 1 //Modify the value of this macro to 1
#defineconfigCPU_CLOCK_HZ (SystemCoreClock )
#defineconfigTICK_RATE_HZ ( (TickType_t ) 1000 )
#define configMAX_PRIORITIES ( 8 )
#define configMINIMAL_STACK_SIZE (( uint16_t ) 128 )

Step 3: Continue to add traceTASK_SWITCHED_IN and traceTASK_SWITCHED_OUT definitions at the end of the FreeRTOSConfig.h header file:

#definetraceTASK_SWITCHED_IN() extern voidStartIdleMonitor(void); \
                                 StartIdleMonitor()
#define traceTASK_SWITCHED_OUT() extern voidEndIdleMonitor(void); \
                                EndIdleMonitor()

Step 4: Include "cmsis_os.h" in the main.h header file
:

#include "stm32f4xx_hal.h"
#include "stm324xg_eval.h"
#include "cmsis_os.h" //Add this header file
//…

Step 5: Modify the project properties so that the compilation process does not require function prototypes:

3

Step 6: In any user code in the project, you can call the osGetCPUUsage() function to get the current CPU usage:
static void LED_Thread2(void const *argument)
{
  uint32_t count;
  uint16_t usage =0;
  (void) argument;

  for(;;)
  {
    count =osKernelSysTick() + 10000;
  
    /* Toggle LED2 every500 ms for 10 s */
    while (count >=osKernelSysTick())
    {
      BSP_LED_Toggle(LED2);
    
      osDelay(500);
    }
    usage =osGetCPUUsage(); //Get the current CPU usage
    /* Turn off LED2 */
    BSP_LED_Off(LED2);
  
    /* Resume Thread 1 */
   osThreadResume(LEDThread1Handle);
  
    /* Suspend Thread 2 */
   osThreadSuspend(NULL);
  }
}
Step 7: Compile and run the test
Use the Live Watch window to monitor the values ​​of all variables osCPU_Usage in the debugging state:

4

osCPU_Usage is a global variable defined in the cpu_utils.c file. It indicates the current CPU usage rate. It is a dynamic value. As shown in the figure above, the dynamic value of CPU usage rate is 20%. In the actual code, the osGetCPUUsage() function is called in step 6 to obtain the current CPU usage rate.

So far, the algorithm usage method has been introduced.

3. Analysis of the algorithm implementation principle
When the operating system is running, it constantly switches between different tasks, and the scheduling process is driven by the system tick. That is, each time a system tick is generated, the environment of the currently running task is checked to determine whether it is necessary to switch tasks, that is, scheduling. If necessary, PendSV is triggered, and the vTaskSwitchContext() function is called in the PendSV interrupt to implement task scheduling. The CPU usage algorithm to be described in this article is to calculate the total amount of time slices occupied by idle tasks within a certain period of time (within 1000 time slices). 100 minus the percentage of idle tasks is the percentage of working tasks, that is, CPU usage.
void vApplicationIdleHook(void)
{
  if( xIdleHandle == NULL )
  {
    /* Store the handle to the idle task. */
    xIdleHandle =xTaskGetCurrentTaskHandle(); //Record the handle of the idle task
  }
}
This function is the idle task hook function. This hook function will be run every time when switching to the idle task. Its function is to record the handle of the current idle task and save it to the global variable xIdleHandle.
void vApplicationTickHook (void)
{
  static int tick = 0;

  if(tick ++ >CALCULATION_PERIOD) //Refresh CPU usage every 1000 ticks  
  {
    tick = 0;
  
    if(osCPU_TotalIdleTime> 1000)
    {
      osCPU_TotalIdleTime =1000;
    }
    osCPU_Usage = (100 -(osCPU_TotalIdleTime * 100) / CALCULATION_PERIOD); //This line of code is the specific calculation method of CPU usage
    osCPU_TotalIdleTime =0;
  }
}
This function is the tick hook function of the operating system, that is, each time a system tick interrupt is generated, it will enter this hook function. This hook function is actually the specific algorithm for calculating CPU usage. osCPU_TotalIdleTime is a global variable, which indicates the total time slice occupied by the idle task within 1000 ticks. The value of CALCULATION_PERIOD macro is 1000, which means the CPU usage is recalculated every 1000 ticks. The

following two functions are how to calculate osCPU_TotalIdleTime:
void StartIdleMonitor(void)
{
  if( xTaskGetCurrentTaskHandle() ==xIdleHandle ) //If it is switched to the idle task
  {
    osCPU_IdleStartTime =xTaskGetTickCountFromISR(); //Record the time point when the idle task is switched
  }
}

void EndIdleMonitor(void)
{
  if( xTaskGetCurrentTaskHandle() ==xIdleHandle ) //If it is switched out from the idle task
  {
    /* Store the handle to the idle task. */
    osCPU_IdleSpentTime =xTaskGetTickCountFromISR() - osCPU_IdleStartTime; //Calculate how long this idle task takes
    osCPU_TotalIdleTime += osCPU_IdleSpentTime;//Accumulate the time occupied by the idle task
  }
}
These two functions are scheduler hook functions, which are called back when the scheduler switches in and out of tasks respectively. The StartIdleMonitor() function records the time point when switching to the idle task, and the EndIdleMonitor() calculates how long the idle task takes when exiting the idle task, and accumulates it to osCPU_TotalIdleTime, which is the total time slice occupied by the idle task.
uint16_t osGetCPUUsage(void)
{
  return (uint16_t)osCPU_Usage; //Directly return the global variable osCPU_Usage, i.e. CPU usage
}
The global variable osCPU_Usage stores the CPU usage, which is recalculated every 1000 ticks in the tick hook function of the operating system.


4 Conclusion
This method can be used to evaluate the operating performance of the STM23 MCU.

 

Keywords:FreeRTOS Reference address:A CPU usage measurement method based on FreeRTOS and its principle introduction

Previous article:Several common reasons for serious MCU function abnormalities
Next article:Explanation of IdMask mode of STM8 CAN bus

Recommended ReadingLatest update time:2024-11-16 20:22

100% autonomous instruction set! Domestic Loongson CPU adapts to 409 products this year
In April 2021, Loongson Zhongke released a new architecture LoongArch (Dragon Architecture) based on a completely independent instruction set, becoming another important force in addition to x86, Arm, and RISC-V. After two years of development, the Loongsonlon architecture has been increasingly improved in terms of
[Embedded]
Software and hardware design of embroidery machine control system based on LH7A404 and LPC2214 CPU chips
introduction With the continuous development of fully automatic embroidery machines, mechanical improvements have not had much effect on improving the performance of the machines. Therefore, the control system has become the key to improving the performance and reducing costs of embroidery machines, and is also the fo
[Microcontroller]
Software and hardware design of embroidery machine control system based on LH7A404 and LPC2214 CPU chips
Introduction to the CPU of MCS-51 single-chip microcomputer
The central processing unit (CPU) of the MCS-51 microcontroller is composed of an arithmetic unit and control logic, including several special function registers (SFRs). 1. ALU-centered arithmetic unit The arithmetic logic unit ALU can perform arithmetic operations such as addition, subtraction, multiplication,
[Microcontroller]
Introduction to the CPU of MCS-51 single-chip microcomputer
Design of single CPU emulator for microcontroller
  Abstract : Based on an in-depth analysis of the storage space structure of the 8051 microcontroller, this article proposes a design scheme for a single CPU emulator based on the microcontroller. This solution is practical, cheap, and highly practical in engineering, and can be used to design new teaching equipment
[Microcontroller]
Intel confirms it will raise prices of CPUs and other chips to cope with rising costs
Intel Corp. has notified customers that it will raise prices on most of its microprocessor and peripheral chip products later this year, largely because of rising costs, multiple people familiar with the matter said today. Intel plans to raise prices this fall on its flagship server and PC processors, as well as a ran
[Semiconductor design/manufacturing]
Intel confirms it will raise prices of CPUs and other chips to cope with rising costs
At91sam9x25 CPU booting issue
Today, a colleague had an RTU that was not working. After debugging, he found that: calibrating delay loop.... It crashed at this part, I searched on Baidu and a user said: This loop is calculating MIPS, the problem may be with the battery or RTC clock! I picked up the oscilloscope and confirmed that the RTC did
[Microcontroller]
At91sam9x25 CPU booting issue
CPU/GPU integrated computing trend CPU performance is the key
The IT industry in 2011 was dominated by intelligence and integration. Since Intel's new generation of Sandy Bridge architecture processors have achieved the ultimate integration, a new round of revolutionary improvements in computer processors has been triggered. Various manufacturers have launched hundreds of noteboo
[Mobile phone portable]
CPU/GPU integrated computing trend CPU performance is the key
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号