MCU task load rate measurement method and system, MCU chip
By using a free-running timer and an interrupt nested counter in the MCU, combined with a dual time accumulator and interrupt context switching compensation, the accuracy problem of CPU load rate measurement in a foreground-background polling architecture is solved, achieving high-precision and accurate CPU load rate measurement.
Patent Information
- Application Number
- CN202611315390.0
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-27
- Publication Date
- 2026-11-17
AI Technical Summary
Existing technologies cannot accurately measure CPU load in foreground-background polling architectures. Interrupt preemption leads to inflated task latency, repeated interrupt time statistics, and uncompensated interrupt context switching overhead, limiting applicability to RTOS systems.
The system uses the MCU's built-in free-running timer to provide a time base, combined with an interrupt nested counter and a dual time accumulator architecture. The interrupt and task times are counted separately through the interrupt service routine time accumulator and the task time accumulator, and the measurement is made accurately through the interrupt context switching overhead compensation value.
It achieves high-precision and accurate CPU load rate measurement, is suitable for foreground and background polling architectures, eliminates interrupt preemption interference, ensures that the measurement results do not exceed 100%, and is suitable for small and medium-sized embedded MCU systems.
Smart Images

Figure CN123114891A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of embedded system technology, specifically to a method and system for measuring MCU task load rate, and an MCU chip. Background Technology
[0002] In the field of embedded systems, the software architecture of microcontroller units (MCUs) is mainly divided into two categories: one is a multi-tasking architecture based on a real-time operating system (RTOS), such as FreeRTOS, μC / OS, and RT-Thread; the other is a foreground / background polling architecture (also known as a bare-metal system or a super-loop system), where the main program consists of an infinite loop that sequentially calls various task functions. Interrupt service routines (ISRs) act as foreground tasks responding to external events, while the main loop acts as a background task executing the main business logic. The foreground / background polling architecture is widely used in small and medium-sized embedded MCU systems due to its advantages such as simple structure, low resource consumption, and controllable real-time performance.
[0003] In the development and maintenance of embedded systems, accurately measuring the CPU load (i.e., CPU utilization) and the time consumed by each task is crucial for evaluating system performance, identifying performance bottlenecks, and optimizing resource allocation. Existing CPU load measurement methods mainly fall into the following categories:
[0004] The first category is measurement methods based on real-time operating systems. For example, the vTaskGetRunTimeStats mechanism provided by FreeRTOS, by configuring a high-precision timer (typically 10 to 20 times the system clock cycle), accumulates the runtime of each task in the task switching hook function, and periodically calculates the proportion of each task's runtime to the total runtime. This method relies on the task switching hooks of the RTOS kernel, is only applicable to RTOS environments, and cannot be applied to kernelless foreground / background polling architectures.
[0005] The second type is the measurement method based on idle task hooks. This method infers CPU utilization by accumulating idle time in the idle task hooks. This method also relies on the RTOS's idle tasks and can only count the overall CPU utilization, not the time spent on individual tasks. It is not suitable for foreground-background polling architectures without idle tasks.
[0006] The third category is measurement methods based on preemption flags. For example, the 2004 paper "How To Calculate CPU Utilization" published by Embedded.com discloses a method for calculating CPU utilization in a foreground / background polling architecture. This method sets a preemption indicator flag in the background loop, setting the flag when an interrupt occurs. Once the background loop detects the flag, it deducts the interrupt duration from the background task's time. This method can only qualitatively determine whether preemption has occurred, cannot accurately quantify the preemption duration, and does not handle interrupt nesting and context switching overhead, resulting in limited measurement accuracy.
[0007] The fourth type is the measurement method based on Program Counter (PC) sampling. This method periodically samples the value of the PC register using a hardware timer and estimates the CPU utilization of each function based on the number of times the PC value falls within different function address ranges. This method is a statistical sampling method, which has statistical errors and cannot accurately measure the time consumption of a single task.
[0008] The aforementioned prior art has the following technical problems:
[0009] (1) Limited applicable architecture: Existing methods are mainly for RTOS or general computer systems and are not applicable to foreground and background polling architecture (bare metal system). Foreground and background polling architecture is widely used in small and medium-sized embedded MCU systems, and there is an urgent need for a CPU load rate measurement method applicable to this architecture.
[0010] (2) Interruption preemption leads to inflated task time: In a foreground-background polling architecture, if a background task is interrupted during execution, the execution time of the interrupt service routine will be included in the background task's time, resulting in the measured task time being higher than the actual value, which cannot reflect the task's true execution efficiency.
[0011] (3) The total CPU utilization rate may exceed 100%: If the interrupt time and task time are simply added together to calculate the CPU utilization rate, the CPU utilization rate will exceed 100% because the interrupt time has been included in the time consumed by the interrupted task, which does not conform to the actual physical meaning.
[0012] (4) Inaccurate time statistics in interrupt nesting scenarios: In MCU systems that support interrupt nesting, if the interrupt time is accumulated for each level of interrupt nesting, the interrupt time will be repeatedly counted, resulting in distorted measurement results.
[0013] (5) Interrupt context switching overhead cannot be compensated: During the interrupt entry and exit process, the MCU hardware will automatically perform register push and pop operations. This part of the time overhead is invisible and cannot be captured by the timer, resulting in the measured interrupt time being less than the actual interrupt time, which affects the measurement accuracy. Summary of the Invention
[0014] The purpose of this invention is to provide a method and system for measuring MCU task load rate, and an MCU chip that can eliminate interrupt preemption interference and reflect the true execution efficiency of tasks, so as to achieve accurate measurement of CPU utilization.
[0015] In a first aspect, the present invention provides a method for measuring MCU task load rate, the method comprising:
[0016] The MCU provides a continuously incrementing time base based on its built-in free-running timer, whose counter wraps back to zero after overflowing.
[0017] At the entry point of the interrupt service routine, an increment operation is performed based on the current value of the interrupt nesting counter, and the current count value of the free-running timer is recorded as the interrupt start time;
[0018] At the exit of the interrupt service routine, the interrupt nesting counter is decremented by one based on its current value, and the current count value of the free run timer is recorded as the interrupt end time. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time and the preset interrupt context switching overhead compensation value. The interrupt execution time is accumulated into the interrupt service routine time accumulator based on the judgment result that the interrupt nesting counter has been decremented to zero.
[0019] Before the background task is executed, the current value of the interrupt service routine time accumulator is read as the starting snapshot. After the background task is executed, the current value of the interrupt service routine time accumulator is read as the ending snapshot. The interrupt preemption time is obtained based on the difference between the ending snapshot and the starting snapshot. The net task time is obtained based on the difference between the total task time of the background task and the interrupt preemption time. The net task time is added to the task time accumulator.
[0020] The CPU utilization rate is output based on the sum of the increments of the interrupt service routine time accumulator and the task time accumulator within the measurement period, and the total time of the measurement period.
[0021] Optionally, based on the sum of the increments of the interrupt service routine time accumulator and the task time accumulator within the measurement period, and the total time of the measurement period, the CPU utilization rate is output, including:
[0022] At the start of the measurement period, the initial values of the interrupt service routine time accumulator and the task time accumulator are recorded.
[0023] At the end of the measurement cycle, record the final value of the interrupt service routine time accumulator and the final value of the task time accumulator;
[0024] The total interrupt service routine time is obtained based on the difference between the final value and the initial value of the interrupt service routine time accumulator, and the total background task time is obtained based on the difference between the final value and the initial value of the task time accumulator.
[0025] The total time of the measurement cycle is obtained based on the difference between the count values of the free-running timer at the end and start times of the measurement cycle.
[0026] The CPU utilization rate is calculated based on the ratio of the sum of the total time of the interrupt service routine and the total time of the background tasks to the total time of the measurement cycle.
[0027] Optionally, the preset interrupt context switching overhead compensation value is obtained through offline calibration, which includes:
[0028] Under conditions of no interrupt nesting, the execution time of multiple interrupts is measured and compared with the execution time of the pure code of the interrupt service routine. The difference is used as the interrupt context switching overhead compensation value. The execution time of the pure code of the interrupt service routine is calculated based on the number of instruction cycles.
[0029] Optionally, the net task time is obtained based on the difference between the total task duration of the background task and the interrupt preemption time, including:
[0030] Before the background task function is called, the current count value of the free-running timer is recorded as the task start time;
[0031] After the background task function is called, the current count value of the free-running timer is recorded as the task end time;
[0032] The total time taken for the task is obtained based on the difference between the task end time and the task start time.
[0033] The net task time is obtained by calculating the difference between the total task time and the interruption preemption time.
[0034] Optionally, it also includes collecting multi-dimensional time consumption data for each background task, including the total time consumption of the task in the current period, the net time consumption of the task in the current period, the historical maximum net time consumption, the historical minimum net time consumption, and the current period task triggering cycle value.
[0035] The total time consumed by the current cycle task is obtained by the difference between the free run timer count value based on the start and end times of the background task, including the interrupt preemption time.
[0036] The current cycle net task time is obtained based on the difference between the total task time and the interrupt preemption time;
[0037] The historical maximum net task time is dynamically updated based on the comparison between the current cycle net task time after each task execution and the historical maximum value.
[0038] The historical minimum net task time is dynamically updated based on the comparison between the current cycle net task time after each task execution and the historical minimum value.
[0039] The current cycle task trigger cycle value is obtained based on the difference between the free-running timer count values at two adjacent task trigger times.
[0040] Optionally, the free-running timer is a free-running hardware timer built into the MCU, and a microsecond-level time base is provided based on the counting frequency of the free-running hardware timer.
[0041] Secondly, the MCU task load rate measurement system of the present invention includes:
[0042] Free-running timers are used to provide a continuously incrementing time base that wraps back to zero after overflowing;
[0043] The interrupt nesting counter is used to increment the counter at the entry point of an interrupt service routine and decrement it at the exit point of the interrupt service routine.
[0044] An interrupt service routine time accumulator is used to accumulate the interrupt execution time based on the judgment result that the interrupt nesting counter has been reduced to zero. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time and a preset interrupt context switching overhead compensation value.
[0045] A task time accumulator is used to accumulate the net task time of a background task. The net task time is obtained based on the difference between the total task time of the background task and the interrupt preemption time. The interrupt preemption time is obtained based on the difference between snapshots of the interrupt service routine time accumulator before and after the execution of the background task.
[0046] The CPU utilization calculation module is used to output the CPU utilization rate based on the sum of the increments of the interrupt service routine time accumulator and the task time accumulator within the measurement period, as well as the total time of the measurement period.
[0047] Optionally, it also includes:
[0048] The multi-dimensional task time consumption statistics module is used to collect multi-dimensional time consumption data for each background task. The multi-dimensional time consumption data includes the total time consumption of the task in the current period, the net time consumption of the task in the current period, the historical maximum net time consumption, the historical minimum net time consumption, and the current period task trigger cycle value.
[0049] Thirdly, the MCU chip described in this invention includes the MCU task load rate measurement system as described in this invention.
[0050] Compared with the prior art, the present invention has the following beneficial effects:
[0051] (1) High precision: This application is based on the FreeRun hardware timer built into the MCU, which provides a microsecond-level time reference. The measurement accuracy is significantly higher than that of existing technologies based on background loop counting or flag bit methods. Taking a 100MHz MCU as an example, the FreeRun timer counting frequency can reach tens of MHz, and the single measurement accuracy is better than 1 microsecond, which can meet the needs of embedded systems for high-precision performance measurement.
[0052] (2) Accuracy: This invention uses a dual-time accumulator architecture and a net task time snapshot calculation method to accurately separate interrupt time and task time, effectively deducting interrupt preemption time, so that the measured net task time truly reflects the execution efficiency of the task itself. The CPU utilization calculation formula ensures that the statistical result does not exceed 100%, which conforms to the actual physical meaning and avoids the problem that the CPU utilization may exceed 100% in the prior art.
[0053] (3) Completeness: This invention uses an interrupt nesting counter mechanism to fully handle multi-level interrupt nesting scenarios, accumulating only the complete execution time of the outermost interrupt once, thus avoiding repeated counting of interrupt times. This mechanism is applicable to various MCU systems that support interrupt nesting, ensuring accurate measurement results in complex interrupt scenarios.
[0054] (4) Compensation: This invention compensates for the invisible overhead of automatic stack pushing and popping by the MCU hardware during interrupt entry and exit through a fixed compensation mechanism for interrupt context switching overhead, thereby improving the accuracy of interrupt time measurement. This compensation mechanism obtains a fixed compensation value through offline calibration, is simple to implement, and has a good compensation effect.
[0055] (5) Applicability: This invention is specifically designed for foreground / background polling architectures (bare-metal systems), and does not rely on task switching hooks or idle tasks in the RTOS kernel. It is suitable for small and medium-sized embedded MCU systems without a kernel. This architecture is widely used in industrial control, automotive electronics, home appliances, and IoT terminals. This invention fills the gap in accurate CPU load rate measurement methods in this field.
[0056] (6) Low overhead: The measurement code of this invention has little impact on system performance. The interrupt service routine entry and exit only add a small number of counter operations and timer reading operations, and the background task start and end only add two timer reading operations. The measurement overhead is negligible and does not affect the system real-time performance.
[0057] (7) Multi-dimensional data support: This invention simultaneously counts data from five dimensions: total task time, net task time, maximum time, minimum time, and task triggering cycle, providing rich data support for system performance analysis and optimization, and helping to identify performance bottlenecks, abnormal situations and optimization directions. Attached Figure Description
[0058] Figure 1 This is the basic architecture of the foreground and background polling operating system in the embodiments of this application;
[0059] Figure 2 This is a block diagram of the MCU task load rate measurement system in the embodiments of this application;
[0060] Figure 3 This is a flowchart of the interrupt nesting process in the embodiments of this application;
[0061] Figure 4 This is a timing diagram of task time measurement in the embodiments of this application;
[0062] Figure 5 This is a flowchart of the MCU task load rate measurement method in the embodiments of this application;
[0063] Figure 6 This is a block diagram of the MCU chip in the embodiments of this application. Attached Figure Description
[0064] 1. Free-running timer; 2. Interrupt service routine time accumulator; 3. Task time accumulator; 4. Interrupt nesting counter; 5. CPU utilization calculation module; 6. Multi-dimensional task time consumption statistics module; 7. MCU chip; 8. MCU task load rate measurement system. Detailed Implementation
[0065] The embodiments of the present invention will be described below with reference to the accompanying drawings and preferred embodiments. Those skilled in the art can understand other advantages and effects of the present invention from the content disclosed in this specification. The present invention can also be implemented or applied through other different specific embodiments, and various details in this specification can also be modified or changed based on different viewpoints and applications without departing from the spirit of the present invention. It should be understood that the preferred embodiments are only for illustrating the present invention and not for limiting the scope of protection of the present invention.
[0066] like Figure 5 As shown in the figure, this application discloses a method for measuring MCU task load rate, the method including:
[0067] The MCU's built-in free-running timer 1 provides a continuously increasing time base, and the free-running timer 1's counter wraps back to zero after overflowing.
[0068] At the interrupt service routine entry point, an increment operation is performed based on the current value of the interrupt nested counter 4, and the current count value of the free run timer 1 is recorded as the interrupt start time.
[0069] At the exit of the interrupt service routine, the interrupt nesting counter 4 is decremented by one based on its current value. The current count value of the free run timer 1 is recorded as the interrupt end time. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time and the preset interrupt context switching overhead compensation value. The interrupt execution time is accumulated into the interrupt service routine time accumulator 2 based on the judgment result that the interrupt nesting counter 4 has been decremented to zero.
[0070] Before the background task is executed, the current value of the interrupt service routine time accumulator 2 is read as the starting snapshot. After the background task is executed, the current value of the interrupt service routine time accumulator 2 is read as the ending snapshot. The interrupt preemption time is obtained based on the difference between the ending snapshot and the starting snapshot. The net task time is obtained based on the difference between the total task time of the background task and the interrupt preemption time. The net task time is accumulated into the task time accumulator 3.
[0071] The CPU utilization rate is output based on the sum of the increments of interrupt service routine time accumulator 2 and task time accumulator 3 within the measurement cycle, and the total time of the measurement cycle.
[0072] In one possible embodiment, the CPU utilization rate is output based on the sum of the increments of the interrupt service routine time accumulator 2 and the task time accumulator 3 within the measurement period, and the total time of the measurement period, including:
[0073] At the beginning of the measurement cycle, the initial values of interrupt service routine time accumulator 2 and task time accumulator 3 are recorded; at the end of the measurement cycle, the final values of interrupt service routine time accumulator 2 and task time accumulator 3 are recorded; the total interrupt service routine time is obtained based on the difference (i.e., increment) between the final and initial values of interrupt service routine time accumulator 2, and the total background task time is obtained based on the difference (i.e., increment) between the final and initial values of task time accumulator 3; the total measurement cycle time is obtained based on the difference between the count values of free-running timer 1 at the end and beginning of the measurement cycle; and the CPU utilization rate is calculated based on the ratio of the sum of the total interrupt service routine time and the total background task time to the total measurement cycle time.
[0074] In one possible embodiment, the preset interrupt context switching overhead compensation value is obtained through offline calibration, which includes:
[0075] Under conditions of no interrupt nesting, the execution time of multiple interrupts is measured and compared with the execution time of the pure code of the interrupt service routine. The difference is used as the interrupt context switching overhead compensation value. The execution time of the pure code of the interrupt service routine is calculated based on the number of instruction cycles.
[0076] In one possible embodiment, the net task time is obtained based on the difference between the total task duration of the background task and the interrupt preemption time, including:
[0077] Before the background task function is called, the current count value of the free-running timer 1 is recorded as the task start time. After the background task function is called, the current count value of the free-running timer 1 is recorded as the task end time. The total task duration is calculated based on the difference between the task end time and the task start time. The net task time is calculated based on the difference between the total task duration and the interrupt preemption time.
[0078] In one possible embodiment, the method further includes collecting multi-dimensional time consumption data for each background task. This multi-dimensional time consumption data includes the total time consumption of the current cycle task, the net time consumption of the current cycle task, the historical maximum net time consumption, the historical minimum net time consumption, and the current cycle task trigger cycle value. The total time consumption of the current cycle task is obtained by comparing the free-running timer 1 count values based on the start and end times of the background task, including interrupt preemption time. The net time consumption of the current cycle task is obtained by comparing the total time consumption of the task with the interrupt preemption time. The historical maximum net time consumption is dynamically updated based on the comparison between the current cycle net time consumption and the historical maximum value after each task execution. The historical minimum net time consumption is dynamically updated based on the comparison between the current cycle net time consumption and the historical minimum value after each task execution. The current cycle task trigger cycle value is obtained by comparing the free-running timer 1 count values based on the start and end times of two adjacent tasks.
[0079] In one possible embodiment, the free-running timer 1 is a free-running hardware timer built into the MCU, providing a microsecond-level time base based on the counting frequency of the free-running hardware timer.
[0080] like Figure 2As shown in the figure, an MCU task load rate measurement system according to an embodiment of this application includes a free-running timer 1, an interrupt nesting counter 4, an interrupt service routine time accumulator 2, a task time accumulator 3, a CPU utilization calculation module 5, and a multi-dimensional task time consumption statistics module 6. The free-running timer 1 provides a continuously increasing time base that wraps back to zero after overflowing. The interrupt nesting counter 4 increments by one at the interrupt service routine entry point and decrements by one at the interrupt service routine exit point. The interrupt service routine time accumulator 2 accumulates the interrupt execution time based on the result of the interrupt nesting counter 4 decrementing to zero. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time, as well as a preset interrupt context switching overhead compensation value. The task time accumulator 3 accumulates the net task time of background tasks. The net task time is obtained based on the difference between the total task consumption of the background tasks and the interrupt preemption time. The interrupt preemption time is obtained based on the snapshot difference between the interrupt service routine time accumulator 2 before and after the background task execution. CPU utilization calculation module 5 outputs CPU utilization based on the sum of the increments of interrupt service routine time accumulator 2 and task time accumulator 3 within the measurement period, and the total time of the measurement period. Multi-dimensional task time consumption statistics module 6 is used to collect multi-dimensional time consumption data for each background task. This multi-dimensional time consumption data includes the total task time in the current period, the net task time in the current period, the historical maximum net task time, the historical minimum net task time, and the task trigger period value in the current period.
[0081] like Figure 6 As shown in the embodiments of this application, an MCU chip includes an MCU task load rate measurement system 8 as described in the embodiments of this application. This application is based on the FreeRun hardware timer (i.e., free-run timer 1) built into the MCU chip 7. The counter of the free-run timer 1 continuously increments and wraps back to zero after overflowing, providing a microsecond-level time reference. This application uses a dual-time accumulator architecture (interrupt service routine time accumulator 2 and task time accumulator 3) to separately count the execution time of the interrupt service routine and the execution time of the background task; it uses an interrupt nesting counter 4 to handle multi-level interrupt nesting scenarios; it uses a fixed compensation value to compensate for the invisible overhead of interrupt context switching; and it uses a snapshot method to calculate the net task time (deducting interrupt preemption time); finally, it calculates the CPU utilization rate according to the formula CPU_Load=(T_ISR+T_Task) / T_Total×100%.
[0082] The following is a detailed description of this application:
[0083] I. Dual-time accumulator architecture
[0084] This application designs a dual-time accumulator architecture, including an interrupt service routine time accumulator 2 (IsrTime) and a task time accumulator 3 (TaskTime). Interrupt service routine time accumulator 2 is used to accumulate the execution time of all interrupt service routines (including context switching overhead compensation), while task time accumulator 3 is used to accumulate the net execution time of background tasks (after deducting interrupt preemption time). The two accumulators, 2 and 3, operate independently without interference, achieving precise separation of interrupt time and task time.
[0085] Before the background task executes, record the current value of interrupt service routine time accumulator 2 (IsrTimeStart) and the current value of task time accumulator 3 (TaskTimeStart); after the background task executes, record the current value of interrupt service routine time accumulator 2 (IsrTimeEnd) and the current value of task time accumulator 3 (TaskTimeEnd). The interrupt preemption time (T_ISR) within the measurement cycle = IsrTimeEnd - IsrTimeStart, the total task time of the background task (T_Task) = TaskTimeEnd - TaskTimeStart, and the total measurement cycle time (T_Total) is calculated from the difference between free-running timer 1. CPU utilization (CPU_Load) = (T_ISR + T_Task) / T_Total × 100%. Since task time accumulator 3 accumulates the net task time (after deducting interrupt preemption time), T_ISR and T_Task do not overlap, and the CPU utilization does not exceed 100%.
[0086] II. Interrupt Nested Counter Mechanism
[0087] For the MCU chip 7 that supports interrupt nesting, this application designs an interrupt nesting counter (IsrNestCnt) 4. At the entry point of the interrupt service routine, IsrNestCnt is incremented by 1; at the exit point of the interrupt service routine, IsrNestCnt is decremented by 1, and it is checked whether IsrNestCnt is 0. Only when IsrNestCnt is decremented to 0 (i.e., when the outermost interrupt exits) is the interrupt execution time (including interrupt context switching overhead compensation) accumulated to the interrupt service routine time accumulator 2.
[0088] This interrupt nesting counter mechanism ensures that in multi-level interrupt nesting scenarios, only the complete execution time of the outermost interrupt (including the execution time of all inner interrupts) is accumulated once, avoiding the problem of duplicate statistics caused by accumulating the execution time of each level of interrupt. For example, when interrupt A is preempted by interrupt B during its execution, and interrupt B is preempted by interrupt C during its execution, the traditional method would accumulate the execution times of interrupts A, B, and C separately, resulting in interrupt B's execution time being counted twice (once within B itself and once within A), and interrupt C's execution time being counted three times. The interrupt nesting counter mechanism of this invention ensures that only the complete execution time of the outermost interrupt A is accumulated once, resulting in accurate measurement results.
[0089] III. Fixed Compensation for Interrupt Context Switching Overhead
[0090] To address the issue that the invisible overhead of automatic stack pushing and popping during interrupt entry and exit cannot be captured by the timer, this application designs a fixed compensation mechanism for interrupt context switching overhead. Through pre-calibration, an interrupt context switching overhead compensation value (ISR_CONTEXT_SWITCH_OVERHEAD_TICKS) is determined. Using timer ticks as the unit, this compensation value is added to the actual measured interrupt execution time (t_IsrDuration) when calculating the interrupt execution time at the interrupt service routine exit.
[0091] Specifically, the timer value (t_IsrStart) is recorded at the entry point of the interrupt service routine, and the timer value (t_IsrEnd) is recorded at the exit point. t_IsrDuration = t_IsrEnd - t_IsrStart + ISR_CONTEXT_SWITCH_OVERHEAD_TICKS.
[0092] The interrupt context switching overhead compensation value is obtained through offline calibration. The calibration method is as follows: under conditions without interrupt nesting, the execution time of multiple interrupts is measured and compared with the pure code execution time of the interrupt service routine (calculated by the number of instruction cycles). The difference is the interrupt context switching overhead compensation value. This compensation mechanism effectively makes up for the invisible overhead such as hardware stack pushing and popping, and improves the accuracy of interrupt time measurement.
[0093] IV. Net Task Time Snapshot Calculation Method
[0094] To address the issue of inflated task execution time caused by interruption and preemption during background task execution in a foreground / background polling architecture, this application designs a net task time snapshot calculation method. Before the background task function is called, the current value of the interrupt service routine time accumulator 2 is read as the starting snapshot (IsrTimeSnapshotStart); after the background task function is called, the current value of the interrupt service routine time accumulator 2 is read again as the ending snapshot (IsrTimeSnapshotEnd). During task execution, the interrupt preemption time (T_IsrPreempt) = IsrTimeSnapshotEnd - IsrTimeSnapshotStart.
[0095] The total task time (T_CostTime) is calculated by the difference between the free-running timer 1 at the task's start and end times (including interrupt preemption time). The net task time (T_TaskTime) = T_CostTime - T_IsrPreempt (minus interrupt preemption time). The net task time is accumulated in the task time accumulator 3 (TaskTime). This snapshot calculation method accurately quantifies the total duration of interrupt preemption during each task execution, ensuring that the measured net task time truly reflects the task's execution efficiency and is unaffected by interrupt preemption.
[0096] V. Multi-dimensional Task Time Statistics
[0097] This application simultaneously tracks the time consumption data of each background task across five dimensions: total task consumption in the current period (curCostTime, including interrupt preemption time), net task consumption in the current period (curTaskTime, excluding interrupt preemption time), historical maximum net task consumption (maxCostTime), historical minimum net task consumption (minCostTime), and the real-time statistical trigger period value of the task in the current period (taskPeriod). Among these, maxCostTime and minCostTime are dynamically updated after each task execution to identify fluctuations and anomalies in task consumption.
[0098] Multi-dimensional task time statistics provide rich data support for system performance analysis and optimization: curCostTime reflects the actual time occupied by the task (including preemption), used to assess the actual CPU usage of the task; curTaskTime reflects the execution efficiency of the task itself, used to identify performance bottlenecks in the task code; maxCostTime and minCostTime reflect the fluctuation range of task time, used to identify abnormal situations (such as sudden increases in data volume, dense interrupts, etc.); taskPeriod provides feedback on the accuracy of the task triggering cycle, used to assess the overall health of task scheduling and execution.
[0099] VI. CPU Utilization Calculation Formula
[0100] The CPU utilization rate (CPU_Load) calculation formula in this application is: CPU_Load = (T_ISR + T_Task) / T_Total × 100%. Since T_ISR and T_Task do not overlap (T_Task has deducted the interrupt preemption time included in T_ISR), their sum does not exceed T_Total. Therefore, CPU_Load does not exceed 100%, which conforms to the actual physical meaning. This formula accurately reflects the actual workload of the MCU within the measurement cycle, providing a reliable basis for system resource evaluation and optimization.
[0101] like Figure 1 As shown, Figure 1 The basic architecture of the foreground / background polling operating system of this application is illustrated, including a main loop (background task) and an interrupt service routine (foreground task). The main loop sequentially calls task 1, task 2, ..., task N, while the interrupt service routine asynchronously responds to external interrupts or internal timer / event interrupts during the execution of the main loop.
[0102] like Figure 3 As shown, Figure 3 The process of nested interrupt handling is shown:
[0103] IsrNestCnt is the interrupt nesting counter 4, which records the current interrupt nesting level. The net interrupt time is only added to IsrTime (i.e., the total time of the current interrupt) when the outermost interrupt exits (IsrNestCnt is reduced to 0). ISR_CONTEXT_SWITCH_OVERHEAD_TICKS is used to eliminate the impact of hardware stack push / pop on measurement accuracy. The inner interrupt time of the nested interrupt is already included in t_IsrEnd-t_IsrStart of the outer interrupt and does not need to be accumulated again.
[0104] like Figure 4 As shown, Figure 4The sequence of task time measurement is shown: Task n starts → Read the task start time TaskStartTime[n] and the initial snapshot IsrSnapShot[n] = isrTime → Execute the task (which may be preempted by interrupts) → First-level interrupt is triggered, and the interrupt start time g_IsrStartTime is recorded → Second-level interrupt is triggered, and the interrupt nesting counter 4 is incremented → All interrupts exit, return to the background task, and accumulate the interrupt execution time isrElapsed1 to isrTime → Subsequent interrupts trigger, repeat the above process, and accumulate the interrupt execution time isrElapsedN to isrTime → Task n ends, calculate totalElapsed (total task time), isrElapsed (interrupt preemption time), taskElapsed (net task time), and update the statistics taskTime, etc.
[0105] Taking the RH850 series MCU chip 7 with a main frequency of 240MHz as an example, the MCU chip 7 has a built-in 32-bit FreeRun hardware timer (counting frequency of 40MHz, that is, counting once every 25 nanoseconds) and supports interrupt nesting.
[0106] I. System Module Composition
[0107] FreeRun Timer 1: Uses the MCU's built-in 32-bit FreeRun hardware timer, configured in freerun mode (the counter continuously increments and wraps back to 0 after overflow), providing a time base with a 40MHz counting frequency.
[0108] Interrupt Service Routine Time Accumulator 2: Global variable IsrTime, used to accumulate the execution time of all interrupt service routines (including the interrupt context switch overhead compensation value (ISR_CONTEXT_SWITCH_OVERHEAD_TICKS). The interrupt context switch overhead compensation value is obtained through offline calibration. In this embodiment, it is calibrated to 38 ticks, i.e. 0.95 microseconds).
[0109] Task Time Accumulator 3: The global variable TaskTime is used to accumulate the net execution time of all background tasks (after deducting interrupt preemption time). A snapshot of IsrTime is read at the start and end times of each task to calculate the total time preempted by interrupts during task execution. The net task time is obtained by subtracting the preempted time from the total task time.
[0110] Interrupt Nesting Counter 4: Global variable IsrNestCnt, used to record the current interrupt nesting level.
[0111] CPU utilization calculation module 5: Calculates CPU utilization based on the formula CPU_Load=(T_ISR+T_Task) / T_Total×100%.
[0112] Multi-dimensional task time statistics module 6: For each task, statistics are collected in five dimensions: curCostTime, curTaskTime, maxCostTime, minCostTime, and taskPeriod.
[0113] II. Work Process
[0114] The workflow of this embodiment is as follows:
[0115] Step 1: During system initialization, configure free-run timer 1 to free-run mode and start free-run timer 1; initialize IsrTime=0, TaskTime=0, IsrNestCnt=0, insert corresponding measurement functions at the entry and exit points of each background task and interrupt, and schedule the total statistics function in an independent 500ms period task, where the statistics period is TotalTime.
[0116] Step 2: At the start of the measurement cycle, before each interrupt and task call begins, the measurement entry function of the task and interrupt will record the start time of the first-level interrupt IsrStartTime = the current value of free-running timer 1, the start time of each task TaskStartTime[taskId] = the current value of free-running timer 1, and the total time snapshot of the current interrupt when each task starts IsrSnapShot[taskId] = the total time of the current interrupt (IsrTime).
[0117] Step 3: The system runs normally, the main loop calls each background task in sequence, and the interrupt service routine responds to external interrupts asynchronously.
[0118] Step 4: During the measurement process, after each interrupt and task call ends, the interrupt measurement exit function will calculate the time consumed by this round of interrupt calls after the last level of interrupt exits, and add it to IsrTime. At the same time, it will complete the time compensation for the interrupt context switching time. The task measurement exit function will calculate the total task time (including the time interrupted by interrupts) by obtaining the current value of the timer and subtracting the TaskStartTime[taskId] recorded when the task starts. At the same time, it will obtain IsrTime, subtract the total interrupt time snapshot when the task starts, and calculate the execution time of interrupts during this round of task execution. The total task time minus the execution time of interrupts during task execution gives the net task time. The net task time is added to TaskTime. At the same time, it will calculate the data such as curCostTime, curTaskTime, maxCostTime, minCostTime, and taskPeriod for individual tasks.
[0119] Step 5: At the end of the measurement cycle, T_ISR=IsrTime, T_Task=TaskTime, T_Total=TotalTime. Calculate CPU_Load=(T_ISR+T_Task) / T_Total×100%, and output the CPU utilization rate and the statistical results of the time consumption of each task.
[0120] III. Implementation of Interruption Measurement Program
[0121] The entry and exit functions of the interrupt measurement program are implemented as follows:
[0122] It is necessary to record the time when the interrupt enters and exits, and calculate the interrupt duration based on the time difference. Since interrupts support nested interrupts, it is necessary to ensure that only the time of the outermost interrupt is accumulated. Use the variable g_IsrNestCnt to record the interrupt nesting level, incrementing by 1 each time an interrupt is entered and decrementing by 1 each time an interrupt is exited. At the same time, since the interrupt measurement function can only be called after the interrupt is triggered and the interrupt handler function is entered, the final measured interrupt duration does not include the context switching time overhead of the outermost interrupt. Therefore, it is necessary to compensate for the context switching time of the outermost interrupt in the statistical interrupt duration.
[0123] When using it, you need to ensure that the ISR measurement function is called in all interrupt handlers (the first function called after an interrupt is triggered, not the deep callback function wrapped inside the interrupt handler). Application example:
[0124] void eiint247(void)
[0125] {Os_Measure_IsrEnter(); / / Start timing
[0126] ADC0_SG4_ISR();
[0127] Os_Measure_IsrExit(); / / End the timer
[0128] }
[0129] IV. Implementation of Background Task Time Measurement
[0130] The entry and exit points for measuring the time consumed by background tasks are implemented as follows:
[0131] Because background tasks can be interrupted by the ISR, the time "stolen" by the ISR during this period must be subtracted when calculating task duration.
[0132] Application example:
[0133] / / Background main loop
[0134] while(1)
[0135] {
[0136] uint8 i;
[0137] uint32 currentCnt = 0u;
[0138] for(i = 0; i < g_osTaskCfg.taskNum; i++)
[0139] {
[0140] currenCnt = GptIf_GetTimerCnt();
[0141] if((sint32)(currenCnt - g_osTaskText[i].taskCnt) >=0)
[0142] {
[0143] Os_Measure_TaskStart(i, currentCnt);
[0144] g_osTaskCfg.taskList[i].taskFun();
[0145] g_osTaskText[i].taskCnt += g_osTaskCfg.taskList[i].taskPeriod;
[0146] Os_Measure_TaskEnd(i);
[0147] }
[0148] }
[0149] }
[0150] V. Implementation of CPU Utilization Calculation
[0151] The CPU utilization calculation is implemented as follows:
[0152] Void Os_Measure_CalcCpuLoad(uint32 interval_us)
[0153] {
[0154] g_SysStats.totalTime=interval_us*OS_TIMER_1US_CNT;
[0155] g_SysStats.cpuLoad=(float32)(g_SysStats.isrTime+g_SysStats.taskTime) / (float32)g_SysStats.totalTime;
[0156] g_SysStats.isrTime = 0;
[0157] g_SysStats.taskTime = 0;
[0158] }
[0159] VI. Effects of the Implementation Examples
[0160] This embodiment is applied in an industrial control MCU system with a measurement cycle of 500ms. The system includes 6 background tasks and 4 interrupt sources. Actual testing shows that the CPU utilization measurement results of this application are stable and do not exceed 100%. The net task time and total time of each task accurately reflect the actual execution efficiency of the task and the impact of interrupt preemption. Compared with existing flag-based methods, the measurement accuracy of this application is improved by approximately 10 times (from milliseconds to microseconds). Compared with existing RTOS-based methods, this application does not require the introduction of an RTOS kernel, is suitable for bare-metal systems, and reduces resource consumption.
[0161] The above embodiments are preferred embodiments of the present invention, but the embodiments of the present invention are not limited to the above embodiments. Any changes, modifications, substitutions, combinations, or simplifications made without departing from the spirit and principle of the present invention shall be considered equivalent substitutions and shall be included within the protection scope of the present invention.
Claims
1. A method for measuring MCU task load rate, characterized in that, The methods include: The MCU provides a continuously increasing time base based on the built-in free-running timer (1), and the counter of the free-running timer (1) wraps back to zero after overflowing; At the entry point of the interrupt service routine, an increment operation is performed based on the current value of the interrupt nesting counter (4), and the current count value of the free-running timer (1) is recorded as the interrupt start time; At the exit of the interrupt service routine, the interrupt nesting counter (4) is decremented by one based on its current value, and the current count value of the free run timer (1) is recorded as the interrupt end time. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time and the preset interrupt context switching overhead compensation value. The interrupt execution time is accumulated to the interrupt service routine time accumulator (2) based on the judgment result that the interrupt nesting counter (4) has been reduced to zero. Before the background task is executed, the current value of the interrupt service routine time accumulator (2) is read as the starting snapshot. After the background task is executed, the current value of the interrupt service routine time accumulator (2) is read as the ending snapshot. The interrupt preemption time is obtained based on the difference between the ending snapshot and the starting snapshot. The net task time is obtained based on the difference between the total task time of the background task and the interrupt preemption time. The net task time is added to the task time accumulator (3). The CPU utilization rate is output based on the sum of the increments of the interrupt service routine time accumulator (2) and the task time accumulator (3) within the measurement period, and the total time of the measurement period.
2. The MCU task load rate measurement method according to claim 1, characterized in that, Based on the sum of the increments of the interrupt service routine time accumulator (2) and the task time accumulator (3) within the measurement period, and the total time of the measurement period, the CPU utilization rate is output, including: At the start of the measurement cycle, the initial value of the interrupt service routine time accumulator (2) and the initial value of the task time accumulator (3) are recorded; At the end of the measurement cycle, the final value of the interrupt service routine time accumulator (2) and the final value of the task time accumulator (3) are recorded. The total interrupt service routine time is obtained based on the difference between the final value and the initial value of the interrupt service routine time accumulator (2), and the total background task time is obtained based on the difference between the final value and the initial value of the task time accumulator (3). The total time of the measurement cycle is obtained by the difference between the count values at the end and start times of the measurement cycle based on the free-running timer (1). The CPU utilization rate is calculated based on the ratio of the sum of the total time of the interrupt service routine and the total time of the background tasks to the total time of the measurement cycle.
3. The MCU task load rate measurement method according to claim 1, characterized in that, The preset interrupt context switching overhead compensation value is obtained through offline calibration, which includes: Under conditions of no interrupt nesting, the execution time of multiple interrupts is measured and compared with the execution time of the pure code of the interrupt service routine. The difference is used as the interrupt context switching overhead compensation value. The execution time of the pure code of the interrupt service routine is calculated based on the number of instruction cycles.
4. The MCU task load rate measurement method according to claim 1, characterized in that, The net task time is calculated by subtracting the total time of a background task from the interrupt preemption time. Before the background task function is called, the current count value of the free run timer (1) is recorded as the task start time; After the background task function is called, the current count value of the free run timer (1) is recorded as the task end time; The total time taken for the task is obtained based on the difference between the task end time and the task start time. The net task time is obtained by calculating the difference between the total task time and the interruption preemption time.
5. The MCU task load rate measurement method according to claim 1, characterized in that, It also includes statistical analysis of multi-dimensional time consumption data for each background task, including the total time consumption of the task in the current period, the net time consumption of the task in the current period, the historical maximum net time consumption, the historical minimum net time consumption, and the current period task trigger cycle value.
6. The MCU task load rate measurement method according to claim 1, characterized in that, The free-running timer (1) is a free-running hardware timer built into the MCU, and provides a microsecond-level time reference based on the counting frequency of the free-running hardware timer.
7. An MCU task load rate measurement system, characterized in that, include: Free-running timer (1) is used to provide a time base that is continuously incremented and wraps back to zero after overflow; The interrupt nesting counter (4) is used to increment the counter at the entry point of the interrupt service routine and decrement the counter at the exit point of the interrupt service routine. Interrupt service routine time accumulator (2) is used to accumulate the interrupt execution time based on the judgment result that the interrupt nesting counter (4) has been reduced to zero. The interrupt execution time is obtained based on the difference between the interrupt end time and the interrupt start time and the preset interrupt context switching overhead compensation value. The task time accumulator (3) is used to accumulate the net task time of the background task. The net task time is obtained based on the difference between the total task time of the background task and the interrupt preemption time. The interrupt preemption time is obtained based on the difference between the snapshots of the interrupt service routine time accumulator (2) before and after the execution of the background task. The CPU utilization calculation module is used to output the CPU utilization rate based on the sum of the increment of the interrupt service routine time accumulator (2) and the increment of the task time accumulator (3) within the measurement cycle, and the total time of the measurement cycle.
8. The MCU task load rate measurement system according to claim 7, characterized in that, Also includes: The multi-dimensional task time consumption statistics module (6) is used to collect multi-dimensional time consumption data for each background task. The multi-dimensional time consumption data includes the total time consumption of the current period task, the net time consumption of the current period task, the historical maximum net time consumption, the historical minimum net time consumption, and the current period task trigger cycle value.
9. An MCU chip, characterized in that, Includes the MCU task load rate measurement system (8) as described in claim 8.
