Analysis of embedded C optimization techniques

Source: Internet
Author: User

Embedded C language Optimization tips

1 OverviewEmbedded system refers to the completion of one or several specific functions of computer systems, with a high degree of automation, rapid response and other advantages, has been widely used in consumer electronics, industrial control and other fields. Embedded systems are subject to the limitations of their hardware and operating environment, Very focused on the time and space efficiency of the Code, it is important to choose a suitable development language. At present, there are many languages available in the development of embedded system, of which the C language is the most widely used. Although programming with C has many advantages, it is based onthe C language and the standard C language of the embedded system have a very big difference.Next I combine the features of the embedded system with some of my own accumulation, and discuss some of the tips of code optimization in programming.
2 features of embedded C languageas a structured programming language, the C language combines many high-level languages Features , with strong functionality and portability. But in the development of the embedded system, the computing power and storage capacity of the system are very limited because of the demand of the low-priced products, so how to make good use of these resources is very important. Developers should be aware of the differences between embedded C and standard C languages, Reduce the generation code length, improve program execution efficiency, and optimize the code in the program design.
3 C code optimization in the programthe C compiler now automatically optimizes the code, but these optimizations are execution speed and code length balance. If you want to get smaller and more efficient code, you need the programmer to manually optimize the code.
4 Definition of variable type

The length of machine code generated by different data types varies considerably, variable type selection the smaller the range, the faster you run and the less memory you use . If you can use a variable defined by a character type (char), do not use an integer (int) variable to define it, do not use a long int for a variable defined with an integer variable, and you can avoid floating-point variables without using floating-point (float) variables. The same type of data type, with or without symbols, also affects the length of the machine code. Therefore, we should choose the data type rationally according to the actual need. Of course, do not exceed the scope of the variable after the definition of the variable, if the scope of the variable to assign value, the C compiler does not error, but the program run the result is wrong, and such errors are difficult to find.

5 Algorithm Optimizationalgorithm optimization refers to the optimization of program space-time complexity: On the PC sequential design generally do not have to pay much attention to the length of the program code, just consider the implementation of the function, but the embedded system must consider the system's hardware resources, in the program design, should try to generate code short algorithm, without affecting the implementation of the program function optimization algorithm.
6 Proper use of macros

using the macro code in a C program can improve the execution efficiency of the program. Macro Code itself is not a function. But it is used like a function. A function call uses the stack of the system to hold the data, while the CPU needs to save and restore the current scene at function calls, to stack and stack, so the function call also requires CPU time. The macro definition does not have this problem: Macro definition only as pre-written code embedded in the current program, do not produce function calls, occupy only a few space, save the argument stack, generate assembly language call calls, return parameters, execute return, etc., thus improving the execution speed of the program . While macros undermine the readability of the program and make troubleshooting more cumbersome, embedding code is often a must for embedded systems to achieve the required performance.

In addition, we want to avoid unnecessary function calls, see the following code:

void Str_print (char *str)  {      int i;      for (i = 0; i < strlen (str); i++)       {          printf ("%c", str[i]);      }  }  void Str_print1 (char *str)  {      int len;      len = strlen (str);      for (i = 0; i < len; i++)      {          printf ("%c", str[i]);      }  }  


Note that the functions are similar in function. However, the first function calls the Strlen function multiple times, and the second function only calls the function strlen once. So the second function is significantly better than the first one.

7 Inline AssemblyThe time-critical parts of the program can be rewritten with inline assembly to bring a significant increase in speed. However, developing and testing assembly code is a hard work, it will take longer, so be careful to choose the part to use the assembly. In the program, there is a80-20 Principles , that is, 20% of the program consumes 80% of the running time, so we want to improve efficiency, the most important is to consider improving that 20% of the code.

8 Improving the efficiency of the circulating languagethe basic way to improve the efficiency of the loop is to reduce the complexity of the loop body in C, which is frequently used in cyclic statements:

(1) in multiple loops, the The longest loop is placed in the outermost layer and the shortest loop is This reduces the number of CPU cross-cutting cycles. As in example 1-1 Efficiency is lower than 1-2 efficiency:

for (j = 0; J <, J + +)  {for      (i = 0; i < i++)      {          ...      }    }//Example 1-1 for  (i = 0; I < 10; i++)  {for      (j = 0, J <; J + +)      {          ...      }    }//Example 1-2  
example 1-1 long cycle in the outer layer, low efficiency, example 1-2 long cycle in the inner layers, high efficiency.

(2) If the loop body has a logical judgment, and the number of cycles, the circular judgment should be moved outside the loop body. as an example 2-1 of the ratio of 2-2 to perform a K-1 judgments, and because the former frequent judgment, interrupted the circulation "pipeline" operation, so that the compiler can not optimize the loop processing, reduce efficiency.

for (i = 0; i < 10000; i++)  {      if (conditional)          statement;      else      statement;  }//Example 2-1 simple but inefficient  if (condition) {for      (i = 0; i < 10000; i++)          statements;  }   else   {for      (i = 0; i < 10000; i++)          statements;  }//Example 2-2 The program department is simple but efficient  

9 Improving the efficiency of switch statementsThe switch statement is a commonly used selection statement in C, which generates if-else-if nested code at compile time, and compares it sequentially, and jumps to the execution of the statement that satisfies the condition when the match is found.
When the case label in a switch statement is many, in order to reduce the number of comparisons, you canPut the conditions that occur at a relatively high frequency first or convert the entire switch statement to a nested switch statement.The case marking with high frequency is placed in the outermost switch statement, and the case label with relatively low relative frequency is placed in the other switch statement. In Example 3, the case label with high incidence is placed in the switch statement of the outer layer, and the occurrence frequency is placed in the default

In the (default) inner switch statement.

switch (expression)  {case      value 1:          statement 1:break;      Case Value 2:          statement 2:break;      ... ...      /* Place low frequency in the switch statement in the inner layer */      default:          switch (expression)          {case              value N:                  statement n:break;              Case Value M:                  statement m:break;              ... ...          }  }  
Example 3 uses nested switch statements to improve program execution efficiency.

10 avoiding the use of standard librariesthe use of the C standard library can speed up development, but many standard library codes are large because the standard library needs to manage all the possible scenarios for the user. For example, the sprintf function in the standard library is very large. A large portion of this huge code is used to process floating-point numbers , if you do not need to format floating-point values (such as%f) in your program, programmers can implement this function with a small amount of code based on the actual situation.
11 using mathematical methods to optimize the programMathematics is the mother of computers, there is no basis for mathematics and the foundation, there is no development of computers, so in the programming process, the use of some mathematical methods will be implemented in order to improve the efficiency of the program. Sometimes this problem is often overlooked, especially for inexperienced programmers. For example: Seeking 1~100 and

sum = 100* (100+1)/2; Mathematical formula. (A1 + an) *N/2

The bitwise operation of the C language can reduce the operation of division and modulo. The bits of data in a computer program are the smallest units of data that can be manipulated, and in theory, "bitwise operations" can be used to complete all operations and operations. Thus, the flexible bit operation can effectively improve the efficiency of the program operation. For example, use Replace division with bit operation area : For example: 128/8->> >> 3;

optimization algorithms and data structures help to improve the efficiency of the Code. Of course, sometimes time efficiency and space efficiency is opposite, at this time should analyze which more important, make the appropriate compromise. In addition, in the optimization of the time not one-sided pursuit of compact code, Because the compact code does not produce high-efficiency machine code.
12 Memory allocation

Due to cost constraints, embedded system memory capacity is limited. All variables in the program, including library functions, stacks, and so on, use limited memory: Global variables are valid throughout the program. The function of the static variable is the whole program. Only dynamic variables in local variables are freed after the function has been executed. Therefore, local variables should be used as much as possible in the program to improve the efficiency of memory usage. The size of the heap in the program is limited by the amount of time remaining after all global data and stack space are allocated, and if the heap is too small, the program cannot allocate memory when needed. The malloc function must be freed with the free function after requesting memory to prevent memory leaks.

13 Select a good infinite loopIn programming, we often need to use infinite loops, the two common methods are while (1) and for (;;). The two methods work exactly the same, but which one is better? Let's look at their compiled code:
Before compiling:
while (1);
After compiling:
MOV eax,1
Test Eax,eax
Je foo+23h
JMP foo+18h
Before compiling:
for (;;) ;
After compiling:
JMP foo+23h

Obviously, for (;;) The instruction is small, does not occupy the register, and does not have the judgment, jumps, is better than while (1).

14 using Memoization to avoid recursive repeat calculations

Considering the Fibonacci (Fibonacci) problem, the Fibonacci problem can be solved by a simple recursive approach:

int fib (n)  {      if (n = = 0 | | n = = 1)       {          return 1;      }      else       {          return fib (n-2) + fib (n-1);      }  }  

Note: Here we consider the Fibonacci series starting from 1, so that the series looks like: 1,1,2,3,5,8, ...


Note: From the recursive tree, we calculate the FIB (3) function 2 times, and the FIB (2) function 3 times. This is a repeating calculation of the same function. If n is very large, the FIB function will be less efficient. memoization is a a simple technique that can be used in recursion to enhance the computational speed. The code for the Fibonacci function memoization is as follows:

int calc_fib (int n)  {      int val[n], I;      for (i = 0; I <=n; i++)      {          val[i] =-1;      Value of the first n + 1 terms of the Fibonacci terms set to-1      }      val[0] = 1;               Value of FIB (0) is set to 1      val[1] = 1;           Value of FIB (1) is set to 1      return fib (N, Val);  }     int fib (int n, int* value)  {      if (value[n]! =-1)       {          return value[n];              Using memoization      }      else       {          value[n] = fib (n-2, value) + fib (n-1, value);          Computing the Fibonacci term      }      return value[n];                Returning the value  }  
in addition to programming skills, in order to improve the efficiency of the system, we often need to make the most possible use of the characteristics of various hardware devices themselves to reduce its operating costs, such as reducing the number of interrupts, the use of DMA transmission mode.

For embedded systems, C language has obvious advantages in terms of development speed, software reliability and software quality. This paper discusses how to make better use of system resources in embedded C language in system development. Of course, there are many ways to optimize your code, and here's just a part of it. Hope to provide some help for the developer, but also welcome message exchange.


Copyright NOTICE: This article is "lend you a second" original article, reproduced please indicate the source.

Analysis of embedded C optimization techniques

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.