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)
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 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.
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]
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]
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]
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]
- Popular Resources
- Popular amplifiers
- Principles and Applications of Single Chip Microcomputers 3rd Edition (Zhang Yigang)
- Metronom Real-Time Operating System RTOS for AVR microcontrollers
- Learn C language for AVR microcontrollers easily (with video tutorial) (Yan Yu, Li Jia, Qin Wenhai)
- ATmega16 MCU C language programming classic example (Chen Zhongping)
Recommended Content
Latest Microcontroller Articles
He Limin Column
Microcontroller and Embedded Systems Bible
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
MoreSelected Circuit Diagrams
MorePopular Articles
- Innolux's intelligent steer-by-wire solution makes cars smarter and safer
- 8051 MCU - Parity Check
- How to efficiently balance the sensitivity of tactile sensing interfaces
- What should I do if the servo motor shakes? What causes the servo motor to shake quickly?
- 【Brushless Motor】Analysis of three-phase BLDC motor and sharing of two popular development boards
- Midea Industrial Technology's subsidiaries Clou Electronics and Hekang New Energy jointly appeared at the Munich Battery Energy Storage Exhibition and Solar Energy Exhibition
- Guoxin Sichen | Application of ferroelectric memory PB85RS2MC in power battery management, with a capacity of 2M
- Analysis of common faults of frequency converter
- In a head-on competition with Qualcomm, what kind of cockpit products has Intel come up with?
- Dalian Rongke's all-vanadium liquid flow battery energy storage equipment industrialization project has entered the sprint stage before production
MoreDaily News
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
Guess you like
- What are the categories of current sources? You will know after reading these
- Newcomer Registration
- How much do you know about how 5G mobile phones are designed to avoid radiation hazards?
- Questions about the PIOR register of Renesas MCU R7F0C004
- I have a LPV821 chip in my hand, and the teacher asked me to compare the package size
- Document Resources | Upgrade again - i.MX6Q development board manual update
- Share: [G-Non-contact object size and shape measurement] G-Fuzhou University-Non-contact object shape measurement
- Research on FFT Implementation Using FPGA
- The virtual machine Ubuntu system runs C language code and Python code
- ADC_DAC Basics