How to Optimize AVR C Language Code (Must Read for Programmers)

Publisher:Delightful789Latest update time:2016-07-18 Source: eefocusKeywords:AVR Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
1. Choose the right algorithm . There are introductions in computer books. Replace the slower sequential search method with a faster binary search or random search
method, and replace the insertion sort or bubble sort method with quick sort, merge sort or root sort, which can greatly
improve the efficiency of program execution. . It is also important to choose a suitable data structure. For example, if you
use a lot of insertion and deletion instructions in a bunch of randomly stored numbers, it will be much faster to use a linked list.
Arrays and pointer statements have a very close relationship. Generally speaking, pointers are more flexible and concise, while arrays are
more intuitive and easy to understand. For most compilers, the code generated by using pointers is shorter and
more efficient than that of arrays. However, in Keil, the opposite is true. The code generated by using arrays is shorter than that of using pointers. .


3. Use the smallest data type possible.
If you can use character type (char) to define a variable, don't use
integer type (int) to define it; if you can use
integer type variables to define a variable, don't use long integer (long int); if you can avoid using floating point type (float), don't
use floating point variables. Of course, after defining a variable, do not exceed the scope of the variable. If
you assign a value beyond the scope of the variable, the C compiler will not report an error, but the program will run wrong, and such errors are difficult
to find.
In ICCAVR, you can set the use of printf parameters in Options. Try to use basic parameters (%c,
%d, %x, %X, %u and %s format specifiers), use less long integer parameters (%ld, %lu, %lx and %lX format specifiers
), and try not to use floating point parameters (%f). The same applies to other C compilers. When other conditions remain unchanged
, using the %f parameter will increase the amount of generated code and reduce the execution speed.

4. Use self-increment and self-decrement instructions.
Usually, the use of self-increment and self-decrement instructions and compound assignment expressions (such as a-=1 and a+=1, etc.) can generate high-quality
program codes. The compiler can usually generate instructions such as inc and dec, while using instructions such as a=a+1 or a=a-1
, many C compilers will generate two to three bytes of instructions. In ICCAVR, GCCAVR, IAR and other C compilers applicable to AVR chips,
the codes generated by the above writing methods are the same, and they can also generate high-quality
codes such as inc and dec.

5. Reduce the intensity of operations
. You can use expressions with small amount of operations but the same function to replace the original complex expressions. As follows:
(1) Remainder operation.
    a=a%8;
can be changed to:
    a=a&7;
Note: Bit operation only needs one instruction cycle to complete, while most C compilers' "%" operations are
completed by calling subroutines, which have long codes and slow execution speed. Usually, if you only need to find the remainder of 2n squares, you can use
the bit operation method instead.

(2) Square operation
    a=pow(a,2.0);
can be changed to:
    a=a*a;
Note: In microcontrollers with built-in hardware multipliers (such as the 51 series), multiplication is much faster than squaring
, because the squaring of floating-point numbers is implemented by calling subroutines. In AVR microcontrollers with built-in hardware multipliers
, such as ATMega163, multiplication can be completed in only 2 clock cycles. Even in AVR microcontrollers without built-in hardware multipliers, the subroutine for multiplication is shorter and faster
than the subroutine for squaring . If the cube is calculated, such as:     a=pow(a,3.0); can be changed to:     a=a*a*a;, the efficiency improvement is more obvious. (3) Use shifting to implement multiplication and division operations     a=a*4;     b=b/4; can be changed to:     a=a<<2;     b=b>>2; Note: Usually, if you need to multiply or divide by 2n, you can use the shifting method instead. In ICCAVR, if you multiply by 2n, you can generate a left shift code, and if you multiply by other integers or divide by any number, you can call the multiplication and division subroutine. The code generated by the shift method is more efficient than the code generated by calling the multiplication and division subroutine. In fact, as long as you multiply or divide by an integer, you can use the shift method to get the result, such as:     a=a*9 can be changed to:     a=(a<<3)+a 6. Loop (1), loop statement For some tasks that do not require loop variables to participate in the operation, they can be placed outside the loop. The tasks here include expressions, function calls, pointer operations, array access, etc. All operations that do not need to be performed multiple times should be grouped together and put into an initialization program of init. (2) Delay function: The commonly used delay function is in the form of self-increment:     void delay (void)     { unsigned int i;     for (i=0;i<1000;i++)     ;     } Change it to a self-decrement delay function:     void delay (void)     { unsigned int i;         for (i=1000;i>0;i--)     ;     } The delay effects of the two functions are similar, but the code generated by almost all C compilers for the latter function is 1 to 3 bytes less than the former code, because almost all MCUs have instructions for branching to 0, and the latter method can generate such instructions.













































The same is true when using a while loop. Using a decrement instruction to control a loop will generate
1 to 3 fewer characters of code than using an increment instruction to control a loop.
However, when there are instructions in the loop that read and write arrays through the loop variable "i", using a pre-decrement loop may cause
the array to exceed its bounds, so be careful.

(3) While loop and do...while loop
There are two loop forms when using a while loop:
unsigned int i;
    i=0;
    while (i<1000)
    {
        i++;
  //user program
    }
or:
unsigned int i;
    i=1000;
    do
    i--;
    //user program
    while (i>0);
Of these two loops, the length of the code generated after compiling using a do...while loop is shorter than that of a while loop.

7. Table lookup
In general, very complex operations are not performed in the program, such as multiplication, division, and square root of floating-point numbers, as well as interpolation operations of some complex
mathematical models. For these operations that consume both time and resources, table lookup should be used as much as possible
, and the data table should be placed in the program storage area. If it is difficult to generate the required table directly, try to start it at startup
to reduce the workload of repeated calculations during program execution.

8. Others
For example, using online assembly and saving strings and some constants in program memory are beneficial to optimization.
Keywords:AVR Reference address:How to Optimize AVR C Language Code (Must Read for Programmers)

Previous article:Fuse Quick Start
Next article:I/O registers and port operations of AVR microcontrollers

Recommended ReadingLatest update time:2024-11-16 16:40

16-bit PWM output program of avr microcontroller TC1
********************************************/   * Operating frequency: Internal 8M *   * Compiler: ICCAVR 6.31A *   * Output: PD4 outputs PWMB, PD5 outputs PWMA *   * The generated PWM frequency is 8M/65536, about 122Hz *   ********************************************/   #include iom16v.h    #include macros.h    //De
[Microcontroller]
Grayscale Design and Implementation of LED Display Screen Based on AVR Microcontroller
  LED dot matrix blocks have the advantages of high brightness, uniform light emission, good reliability, and easy assembly, and can form display screens of various sizes. At present, LED display screens have been widely used in text display and have achieved good results, but most of them can only display scrolling te
[Microcontroller]
Grayscale Design and Implementation of LED Display Screen Based on AVR Microcontroller
Fuse Quick Start
The way the STK500 handles fuses in AVR Studio has a huge advantage: it is user configurable in groups of functions. Compared with PnoyProg2000, SL-ISP, this method has the following advantages (the advantages are so obvious that they can be described as "huge advantages"):      1. Effectively avoid chip lockup due
[Microcontroller]
IAR for AVR does not erase EEPROM when configuring JTAGICE mkII emulation
{Business needs} Sometimes we want to use the parameters configured in EEPROM during simulation, instead of resetting them every time. {Configuration method} Project- Right click- Debugger- JTAGICE mkII- JTAGICE mkII2 Select Preserve EEPROM contents even if device is reprogrammed as follows
[Microcontroller]
IAR for AVR does not erase EEPROM when configuring JTAGICE mkII emulation
Design of comprehensive performance testing equipment for laser rangefinder based on AVR
Since the traditional laser rangefinder performance test must be carried out outdoors to test the target and is restricted by weather conditions, the technical survey and daily maintenance are greatly restricted. In order to overcome the above problems, the author designed a laser rangefinder comprehensive performance
[Microcontroller]
Design of comprehensive performance testing equipment for laser rangefinder based on AVR
AVR MCU PCF8591 conversion example source program operation library
Target system: Based on AVR microcontroller                                                  Application software: ICCAVR                                                       Version: Version 1.0                                                        Experimental content: Initialize, read AD, output DA, use the LED o
[Microcontroller]
AVR MCU external interrupt 0, 1, 2 detailed explanation
Interrupts basically include: 1. Interrupt source 2. Interrupt vector (interrupt entry address) 3. Interrupt priority 4. Interrupt function In addition, in the microcontroller, the execution of an interrupt or the triggering of an interrupt must comply with the following rules: Interrupt trigger | execution
[Microcontroller]
Application design of LED lighting control system based on AVR microcontroller
1 LED lighting control system principle   The system schematic is shown in Figure 1. When the infrared receiver receives the infrared remote control signal, the AVR microcontroller is awakened from sleep mode through an external interrupt; the AVR microcontroller starts to parse the infrared signal, and if it matche
[Microcontroller]
Application design of LED lighting control system based on AVR microcontroller
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号