Home / Learn Chip Programming / Optimising Code Size and Speed

Optimising Code Size and Speed

Make firmware fit and run faster: measure first, then optimise.

In shortMake firmware fit and run faster: measure first, then optimise.

Theory in plain words

Optimisation loopMeasureFind hot spotChange one thingMeasure again
Optimisation loop

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

Compare two implementationsTry it Yourself

A table lookup is 200 times faster than soft-float sin(). The best optimisation is often a different algorithm.

Measure with the Cortex-M cycle counter
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
GoalTricks
Smaller flash-Os, -ffunction-sections + --gc-sections, LTO, newlib-nano, remove printf float, const tables, avoid big libraries
Smaller RAMsmaller types, reuse buffers, avoid large stack arrays, move constants to flash
Fasterbetter algorithm, integer maths, lookup tables, inline small functions, keep hot data in fast RAM / TCM, use DMA
Lower powerfinish quickly then sleep, lower clock when idle, disable unused peripherals
Careful:Always re-run your tests after optimisation. Aggressive options expose bugs such as missing volatile or undefined behaviour.

Quick quiz

1. First step in optimising?

2. Often the biggest speedup?

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.