C code optimisation
Submitted by Webbot on September 17, 2008 - 10:47pm.
This tutorial will discuss various aspects of code optimisation – (I’m a Brit so we use an ‘s’ not a ‘z’ - let’s just get that out of the way now!).This an enormous, and maybe emotive, subject so be prepared to do a lot of reading !
We will cover items such as:-
* How optimisation works (using a pretend processor and pretend compiler)
* Discuss my 'post-boy' and 'post-boy-supervisor' and 'wash-your-hands' analogies
* The register, volatile and const keywords
* Look at how to change optimisation via your makefile
* Considerations to be given when interrupts or multiple threads are accessing the same data
* How to minimise the amount of code you write by using structures for 'data-driven-programming'. ie like C++ but in C.
Although we will be specifically looking at the AVR microcontrollers and the free avr C compiler, many of these principals apply to other environments, and languages, but you may have to dig around in the documentation for your specific compiler to find the associated equivalent.
Code optimisation covers a myriad of things but can be split down into several basics:-
- How to get the compiler to help you to optimise the code you have written by changing command line arguments in your makefile. This means you don’t need to change your code but you will benefit from having a basic understanding of what the compiler is doing on your behalf. Obviously the compiler can only ‘do so much’ – and is no replacement for…
- How to write more optimal code in the first place
Also ‘optimisation’ can mean different things to different people, and can also mean something different depending upon what it is that you are trying to do:-
- Sometimes we want the code to run as fast as possible (even at the expense of requiring extra memory) , or,
- We want the code to take up as little space as possible (at the expense of speed)
- Sometimes we want to use both of these methods. For example: you may want an interrupt service routine to run as fast as possible, whereas your main code may be optimised for space so that it fits in the limited memory available on a specific chip.
It may appear strange that you have options for both speed and size as you probably think that smaller code will run faster and so small=fast. As a general rule this is normally correct – but not always. More later.