Home / Learn Chip Programming / Optimising Code Size and Speed
Optimising Code Size and Speed
Make firmware fit and run faster: measure first, then optimise.
Theory in plain words
What it is
Tools: -Os/-O2, link-time optimisation (LTO), map file analysis, profiling with cycle counters (DWT), choosing algorithms and data layouts, using hardware (DMA, FPU).
Why we use it
Flash and RAM limits and battery life decide product cost. Premature optimisation wastes time; targeted optimisation of the hot path pays.
How it works
Measure with DWT_CYCCNT or a GPIO pin on a scope, find the hot function, try a better algorithm, then compiler flags, then assembly as a last resort.
Where it is used
- Fitting into 32 KB
- Reducing power by sleeping sooner
- Real-time audio and control loops
Cycle counter timing
A table lookup is 200 times faster than soft-float sin(). The best optimisation is often a different algorithm.
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
uint32_t t0 = DWT->CYCCNT;
heavy_function();
uint32_t cycles = DWT->CYCCNT - t0; // exact cycles used| Goal | Tricks |
|---|---|
| Smaller flash | -Os, -ffunction-sections + --gc-sections, LTO, newlib-nano, remove printf float, const tables, avoid big libraries |
| Smaller RAM | smaller types, reuse buffers, avoid large stack arrays, move constants to flash |
| Faster | better algorithm, integer maths, lookup tables, inline small functions, keep hot data in fast RAM / TCM, use DMA |
| Lower power | finish quickly then sleep, lower clock when idle, disable unused peripherals |
Quick quiz
1. First step in optimising?
Find the real hot spot first.
2. Often the biggest speedup?
Algorithms beat micro-tuning.
Common questions
First step in optimising?
Measure. Find the real hot spot first.
Often the biggest speedup?
A better algorithm or table. Algorithms beat micro-tuning.