How to Improve the Efficiency of C Language Code for MCU

Publisher:CuriousTravelerLatest update time:2015-03-26 Source: diangonKeywords:MCU Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
     Code efficiency includes two aspects: code size and code execution speed. If the code is concise and the execution speed is fast, we say that the code is efficient. Generally speaking, the code is simplified and the speed is correspondingly improved. The ROM and RAM space of the microcontroller are very limited. When you encounter insufficient ROM and RAM of the microcontroller during programming, or your program requires a higher execution speed, we have to face the problem of code efficiency. How to improve code efficiency? Now I will discuss with you using a program that flashes an LED as an example.

#include //Include header file

sbit led=P2^0; //define the bit variable led to associate it with the microcontroller pin P2.0

void Delayms(unsigned int t); //define delay function

int main(void) //Main function (C language program entry function)

{

       while(1)

       {

             led=0; //Pull P2.0 low to light up the LED

             Delayms(500); //Call the delay function, delay 500 milliseconds

             led=1; //P2.0 is pulled high to turn off the LED

             Delayms(500); //Call the delay function, delay 500 milliseconds

       }

       return 0;

}

void Delayms(unsigned int t)//delay function

{

        unsigned int i,j;

        for(i=0;i

               for(j=0;j<120;j++);//Delay about 1 millisecond

}

        This is the C source code for the LED flashing indicator. The program code generated by this source code in Keil uVision4 is 67 bytes. Next, we will use several methods to improve the efficiency of this program.

1. Try to define local variables

        The global variables of the microcontroller program are generally placed in the general data memory (RAM), while the local variables are generally placed in the special function registers. The processing speed of register data is faster than that of RAM data. If a global variable is called in a local function, several more codes will be generated. Therefore, define fewer global variables and more local variables. As in the above example, if i and j in the delay function are defined as global variables, the compiled program code will increase to 79 bytes, 12 bytes more.

2. Omitting function definitions

        In a single-chip program, we are used to defining the called function before the main function, and then implementing the called function below the main function. This is certainly a good habit, but each time a function is defined, several codes will be added, and the larger the function parameter data type and the more parameters, the more codes will be added, which is obviously not a good thing. What if the compiler reports an error without defining it? The compilation order of the C compiler is from top to bottom. As long as the called function is implemented before the main function is called, there will be no problem. Therefore, the author's habitual writing method is not to define the function, but to write the function implementation in order (the called function must be written before the main function), and then write the main function at the end. In this way, the compiler will not report an error, and the code will be streamlined. As in the above example, the definition of the delay function is deleted, and then the implementation of the delay function is moved above the main function. After compilation, the program code is reduced to 63 bytes, a reduction of 4 bytes. [page]

3. Omitting function parameters

        Functions have formal parameters in order to pass actual parameters when calling the function. This not only avoids duplicate code, but also allows functions to be called multiple times and different functions to be implemented by passing different actual parameter values, and the overall code will be streamlined. In actual programming, as long as we pay attention, we can further streamline the code. For functions that are not called multiple times or are called multiple times but the actual parameter values ​​remain unchanged, we can omit the function parameters. For example, in the delay function in the above example, we change it into a function without formal parameters:

void Delayms()//delay function

{

     unsigned int i,j;

     for(i=0;i<500;i++)

          for(j=0;j<120;j++);//Delay about 1 millisecond

}

After compilation, the program code becomes 56 bytes, which is 11 bytes less.

4. Change Operator

       Perhaps you may not have noticed that the use of C operators will also affect the amount of program code. For example, in the above example, after changing the self-increment operator in the delay function to a self-decrement operator, such as:

void Delayms(unsigned int t)//delay function

{

     unsigned int i,j;

     for(i=t;i>0;i--)

          for(j=120;j>0;j--);//#p#Page title#e#About 1 millisecond delay

}

After compilation, the program code becomes 65 bytes, which is 2 bytes less.

Other examples of code simplification by replacing operators include:

1. Change the remainder operation expression to a bitwise AND operation expression. For example, b=a%8 can be changed to b=a&7.

2. Change the multiplication expression to a left shift expression. For example, b=a*8 can be changed to b=a<<3.

3. Change the division operation expression to a right shift operation expression. For example, b=a/8 can be changed to b=a>>3.

5. Choose the appropriate data type

        In C language, the choice of variable data type is very particular. If the data type of the variable is too small, it cannot meet the requirements of the program. If the data type of the variable is too large, it will occupy too much RAM resources. You may not have noticed that the data type definition also affects the size of the program code, and this impact is not small. As shown in the above example, the data type defined by the local variable j in the delay function is obviously too large. If it is changed from unsigned int to unsigned char. After compilation, the program code becomes 59 bytes, which is 8 bytes less.

6. Directly embed code

        If a function is only called once in your program and you want the code to execute faster, it is recommended that you do not call the function, but embed the code in the function directly into the main calling function, which will greatly improve the code execution efficiency.

7. Use efficient C statements

        There is a ternary operator "?" in C language, commonly known as "question mark expression". Many programmers like to use it because of its clear logic and concise expression.

Look at this question mark expression: c=(a>b) ? a+1 : b+1; is actually equivalent to the following if...else structure:

if (a>b) c=a+1;

else c=b+1;

As you can see, the question mark expression is quite concise, but its execution efficiency is very low, far less efficient than if...else statement. Therefore, if your program requires faster execution, it is recommended that you do not use the question mark expression.

        In addition, the do...while statement is also more efficient than the while statement.

The efficiency of the code is not the main problem in our programming, except when the program requires a higher execution speed or the ROM and RAM of the microcontroller are insufficient. In general, we don't need to care about it. If you blindly pursue high-efficiency code, it may affect the readability and maintainability of the code.

Keywords:MCU Reference address:How to Improve the Efficiency of C Language Code for MCU

Previous article:Sharing of learning experience of microcontroller beginners
Next article:How to learn single chip microcomputer

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号