Getting the software to work is not sufficient for most embedded systems but also your system needs the same job done at a low cost (less memory and less time). In this series of tutorials, we will mention related topics about code optimization part by part.
In the first part, we will explain how to increase the code efficiency. Current compilers offer code optimization with a trade-off between code size and execution speed. It depends to the programmer’s choice to make the code either smaller or faster. Most of the time, writing efficient code is easier than shortening the code size. So make your code more efficient and let the compiler optimizer to shorten your code size.
1 – Inline Functions
When a function is called frequently in your code, then it is better to add inline to declaration of that function. So that the compiler replaces all calls with the codes inside the function. This method eliminates the function overhead associated with the function call but increases the code size. This method clearly shows the trade-off between the code size and execution time.
2 – Table Lookups
Switch statement codes are commonly used programming techniques. Place the most likely cases first and least likely cases last. This will reduce the average execution time.
3 – Hand-coded Assembly
To make the code work more efficient, some parts of software can be written in assembly language. A good programmer can write better assembly language than the average compiler do.
4 – Global Variables
It is more efficient to use global variables than to pass a parameter to a function. This eliminates the need to push the parameter onto the stack before the function call and pop it back off after the function completed. Most efficient way to use any subroutine would have no parameters at all. However, due to the modularity goals, software engineering community discourages the use of global variables.
5 – Fixed-point Arithmetic
Handling with floating variables costs so much time to your processor unless your target processor does not include floating point unit (FPU). If you use floating-point for a few calculations, these floating point operations can be replaced using fixed-point arithmetic even though it is hard to implement in software, it is still possible.