Performance Optimization for Constrained Devices Questions
Optimizing software that runs on a resource-constrained device or platform, not a server or cloud fleet: mobile apps, embedded and IoT firmware, and game clients operating under hard limits on memory, CPU, battery, and bandwidth. Covers memory and CPU envelope budgeting, power and energy efficiency, platform-specific profiling and toolchains (ARM/MCU debugging, RTOS scheduling), firmware-level concurrency and interrupt handling (ISR design, DMA, priority inversion, lock-free versus locking trade-offs), fixed-point arithmetic and numeric-precision trade-offs on FPU-less hardware, binary and asset size reduction, and on-device model or asset compression. Explicitly excludes server-side, cluster, or cloud-fleet performance work (profiling a Kubernetes service, tuning JVM garbage collection on a backend, scaling a distributed cache) even when phrased as optimizing under constraints: that content belongs to this catalog's server-performance topics.
For a battery-operated device that occasionally performs CPU-intensive tasks, design a power-aware scheduler and DVFS strategy (assuming DVFS is supported) to minimize energy consumption while meeting real-time deadlines. Include energy models, decision heuristics for picking frequency and voltage, handling DVFS transition overhead, and validation strategies on actual hardware.
Sample Answer
Framing
Dynamic voltage and frequency scaling (DVFS) lets the system run the CPU at a lower voltage and clock frequency to save power when full speed isn't needed, at the cost of taking longer to finish the work. For a battery-operated device with occasional CPU-intensive bursts and real-time deadlines, the design question is which frequency to pick for a given task, and when.
Energy model
dynamic power ~ C * V^2 * f
energy for a fixed amount of work ~ (C * V^2 * f) * (work / f) = C * V^2 * work
Intuition: dynamic power scales with frequency, but the time to do a fixed amount of work scales inversely with frequency, so they roughly cancel and energy for a fixed workload depends mainly on voltage, not frequency, in this simplified model. What breaks that cancellation is that voltage itself has to increase disproportionately at the highest frequency bins to keep the circuit stable (the chip needs a bigger voltage margin to switch reliably that fast), so energy actually rises steeply for the last increment of frequency near the top of the range, well before you'd expect from the frequency term alone. There's also static (leakage) power, which is roughly proportional to time the chip stays powered on regardless of frequency, so running slower for longer accumulates more leakage energy than running fast and idling sooner.
To make the cancellation and the voltage penalty concrete, plug in a few illustrative operating points for a hypothetical chip (arbitrary units, not measured silicon, just to show the shape of the formula: C=1, a fixed amount of work=100 units, so time = work / f):
Point A (V=1.0, f=100): power = 1 * 1.0^2 * 100 = 100; time = 100/100 = 1.0; energy = 100 * 1.0 = 100
Point A' (V=1.0, f=150): power = 1 * 1.0^2 * 150 = 150; time = 100/150 = 0.667; energy = 150 * 0.667 = 100
Point B (V=1.2, f=150): power = 1 * 1.2^2 * 150 = 216; time = 100/150 = 0.667; energy = 216 * 0.667 = 144
Points A and A' hold voltage fixed and raise frequency from 100 to 150: energy comes out identical (100 both ways), that's the "roughly cancels" claim made visible. Point B reaches the same 150 frequency but by also raising voltage to 1.2V, and energy jumps 44% to 144, even though the task still finishes in the same 0.667 time units as A'. That's the disproportionate voltage cost near the top of the frequency range, and it's exactly why the energy-minimal point often sits a bit below max frequency rather than at it.
Decision heuristics
- Race-to-idle as the default instinct: for many workloads, finishing fast at a reasonably high frequency and then entering deep sleep beats running slowly the entire time, because it minimizes the time spent paying static/leakage power.
- But not necessarily the very top frequency bin: because voltage rises disproportionately near the top of the frequency range, the actual energy-minimal point is often somewhat below max frequency, close enough to race-to-idle's benefit without paying the steep top-end voltage cost. The practical approach is to profile a handful of candidate (frequency, voltage) operating points for the real workload and measure energy at each, rather than assuming either extreme (always max, or always minimum-that-meets-the-deadline) is correct.
- Deadline-aware floor: never pick a frequency so low that the task risks missing its real-time deadline; the achievable frequency range is bounded below by the deadline and the task's worst-case work, not just by an energy-minimization search.
Handling DVFS transition overhead
Changing frequency and voltage isn't instantaneous, the phase-locked loop (PLL) needs to relock and the voltage regulator needs to settle, which takes real time (typically tens of microseconds) during which the CPU may stall or run at a reduced, unstable clock. So the scheduler shouldn't re-optimize frequency for every individual task; instead, group tasks into a small number of frequency "bins" and only transition between bins when there's a real difference in load, avoiding the case where transition overhead itself eats into or exceeds the energy savings from the switch.
Validation on actual hardware
The energy model above is a simplification (it doesn't capture the real voltage-frequency curve for this specific silicon, real leakage behavior, or actual transition costs), so I'd validate every candidate operating point with a real power measurement on the target board (joules per completed job, measured with a power monitor, not just estimated), across a representative task mix, and separately confirm the chosen policy still meets its deadlines under worst-case task arrival and worst-case transition timing, not just the average case.
Describe the purpose of the C 'volatile' qualifier in embedded firmware. Explain how volatile interacts with compiler optimizations, memory-mapped registers, and concurrent access from ISRs and DMA. Explain a scenario where 'volatile' is insufficient (e.g., atomic operations, memory barriers) and what mechanisms to use instead.
Sample Answer
Definition
volatile tells the compiler "this variable's value can change outside the normal flow of this code, so don't optimize away or reorder accesses to it." Without it, the compiler assumes a variable only changes through code it can see, and is free to cache its value in a register, skip what looks like a redundant read, or reorder accesses relative to other code.
Interaction with compiler optimizations
With volatile, every read and write in source order becomes a real memory access: none can be hoisted out of a loop, cached in a register across iterations, or eliminated as "dead" even if nothing in the visible code appears to use the result.
Memory-mapped registers
A hardware register, such as a UART status register, can change value because of hardware activity, not because of anything your code did. Without volatile, the compiler might read it once and treat it as unchanged forever:
/* Peripheral struct as the vendor header would declare it */
typedef struct {
volatile uint32_t STATUS; /* FIX: volatile so every read re-checks hardware */
volatile uint32_t DATA;
} UART_TypeDef;
#define UART ((UART_TypeDef *)UART_BASE_ADDRESS)
/* BUG if STATUS were declared as a plain (non-volatile) uint32_t above:
* the compiler could read it once, decide the loop condition never
* changes, and either spin forever or optimize the loop away entirely.
* With STATUS declared volatile as above, this loop is correct: */
while (!(UART->STATUS & TX_READY)) {}
ISRs and DMA
The same pattern applies to any variable shared between the main loop and code that runs asynchronously to it, an ISR (interrupt service routine, the function the CPU jumps to when a hardware interrupt fires) or a DMA (Direct Memory Access) controller writing to memory on its own. Main-loop code polling a flag the ISR sets must see the ISR's write, so the flag needs volatile:
volatile int ready = 0;
void wait_for_isr(void) { while (!ready) {} }
void ISR_Handler(void) { ready = 1; }
Without volatile here, the compiler could cache ready in a register inside wait_for_isr and never notice the ISR's write, spinning forever even though the flag really did change.
Where volatile is insufficient
volatile guarantees accesses aren't optimized away or reordered relative to each other; it does not guarantee atomicity, cross-variable memory ordering, or mutual exclusion.
- Atomicity: a
volatile uint64_t counteron a 32-bit MCU (microcontroller unit, the chip running this code) is read or written as two separate 32-bit accesses; an ISR firing between them can see a torn value. Fix: a hardware atomic operation, or a critical section (disable interrupts around the access). - Memory ordering:
volatiledoesn't stop out-of-order execution or insert a hardware memory barrier for DMA coherency. Fix: explicit barriers (__DMB,__DSBon ARM) and cache clean/invalidate operations around a DMA buffer handoff. - Compound read-modify-write:
flags |= BITon a volatile variable is still a non-atomic read-then-write at the machine-code level, an interrupt landing between the two steps loses whichever side updated last. Fix: an atomic bit-set instruction where available, or a critical section around the whole read-modify-write.
You are developing firmware for an embedded device with only 256KB RAM and no dynamic memory allocation. Sensor readings must be sorted in-place as they arrive in small batches. Which sorting algorithm would you choose, how would you manage recursion and stack usage, and how would you handle continuous arrival of readings that exceed memory capacity?
Sample Answer
Approach
With 256KB of RAM and no dynamic memory allocation (everything has to be statically sized up front, no malloc), the algorithm choice is driven as much by memory shape and stack safety as by raw speed. I'd pick insertion sort for the sort itself, and a statically-allocated double-buffer (ping-pong) scheme for handling continuous arrival.
Why insertion sort: it sorts fully in-place with O(1) extra memory, it's completely iterative (no recursion at all, so zero risk of stack overflow from the sort itself), and for the small batch sizes sensor windows typically use (tens of readings, not thousands), its simple inner loop actually beats more "efficient" O(n log n) algorithms in practice because of low constant-factor overhead and no call/recursion cost. Quicksort's average case is faster asymptotically, but its worst-case recursion depth is O(n), which is a real stack-overflow risk on a memory-constrained target with a small fixed stack; even an iterative quicksort needs an explicit stack sized for the worst case. Heapsort is a reasonable fallback for larger batches: fully iterative, O(1) extra memory, and a guaranteed O(n log n) worst case, at a higher constant-factor cost than insertion sort for small n.
Managing recursion and stack usage
I ruled out any recursive algorithm here specifically because the whole point of the constraint is a small, fixed stack. If a future requirement pushed batch sizes up and heapsort or quicksort became necessary, I'd still implement it iteratively with an explicit, statically-sized stack array (sized to log2(max_batch_size), which is small and known at compile time), and always process the smaller partition first so the explicit stack never grows past that bound.
Handling continuous arrival that exceeds capacity
#include <stdint.h>
#include <stdio.h>
#define BATCH_CAP 16 /* fits easily within a 256KB budget */
typedef struct {
uint16_t data[BATCH_CAP];
uint8_t count;
} Batch;
static Batch batch_a, batch_b;
static Batch *filling = &batch_a;
static Batch *ready = NULL; /* sorted batch waiting for the consumer */
static uint32_t dropped_readings = 0;
static void insertion_sort_inplace(uint16_t *arr, uint8_t n) {
for (uint8_t i = 1; i < n; i++) {
uint16_t key = arr[i];
int8_t j = (int8_t)i - 1;
while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; }
arr[j + 1] = key;
}
}
void on_reading_arrived(uint16_t value) {
if (filling->count < BATCH_CAP) {
filling->data[filling->count++] = value;
return;
}
insertion_sort_inplace(filling->data, filling->count);
if (ready != NULL) {
/* consumer hasn't drained the last batch: apply backpressure */
dropped_readings += filling->count;
filling->count = 0;
filling->data[filling->count++] = value;
return;
}
ready = filling;
filling = (filling == &batch_a) ? &batch_b : &batch_a;
filling->count = 0;
filling->data[filling->count++] = value;
}
static int is_sorted(const uint16_t *arr, uint8_t n) {
for (uint8_t i = 1; i < n; i++) {
if (arr[i - 1] > arr[i]) return 0;
}
return 1;
}
int main(void) {
/* A fixed, deterministic stream of 16 readings. */
uint16_t stream[16] = {842, 17, 305, 6001, 88, 4, 1200, 501,
29, 7000, 3, 654, 210, 9999, 61, 400};
for (int i = 0; i < 16; i++) {
on_reading_arrived(stream[i]);
}
/* The 16th reading filled the batch to BATCH_CAP, but a full batch is
* only sorted and handed off to `ready` when the *next* reading arrives,
* so one more arrival is what actually triggers the sort. */
on_reading_arrived(777);
printf("batch full and handed off after the 17th reading: %s\n",
ready != NULL ? "yes" : "no");
printf("ready batch count=%u, is_sorted=%s\n",
ready->count, is_sorted(ready->data, ready->count) ? "yes" : "no");
printf("ready batch: ");
for (uint8_t i = 0; i < ready->count; i++) {
printf("%u%s", ready->data[i], i + 1 < ready->count ? " " : "\n");
}
printf("dropped_readings so far=%u\n", dropped_readings);
/* Continue accepting new readings into the other buffer while the
* first sorted batch is still "ready" (not yet drained by a consumer). */
on_reading_arrived(555);
printf("filling buffer now holds %u reading(s) while ready batch waits\n",
filling->count);
return 0;
}
Output
batch full and handed off after the 17th reading: yes
ready batch count=16, is_sorted=yes
ready batch: 3 4 17 29 61 88 210 305 400 501 654 842 1200 6001 7000 9999
dropped_readings so far=0
filling buffer now holds 2 reading(s) while ready batch waits
Compiled with clang -Wall -Wextra -O2 and run unchanged, verified byte-identical across two runs: the batch fills, gets sorted in-place with insertion sort, and hands off a correctly-sorted batch (confirmed by is_sorted), while the other buffer keeps accepting new readings behind it.
Key points
- Two statically-sized buffers (no
malloc) let the sort happen on one buffer while new readings land in the other, so sorting never blocks incoming data. - If the consumer falls behind and both buffers would otherwise be needed, the device applies explicit backpressure (drop the oldest full batch and count the drop) rather than growing memory unboundedly or blocking the producer indefinitely.
Complexity
Insertion sort is O(n^2) worst case, but for small, bounded batch sizes (n in the tens) that's a small constant amount of work with essentially zero overhead per element, which beats the setup and call overhead of an O(n log n) algorithm at this scale.
Edge cases
- Consumer permanently stalled: drops accumulate forever, so I'd expose
dropped_readingsto a health/telemetry path so a persistent stall is visible, not silent. - Batch size larger than
BATCH_CAPin a single burst: this design assumes bounded arrival rate; a true burst overrun needs either a larger static buffer sized to the true worst case, or explicit rate limiting upstream. - Very small batches (n <= 1): insertion sort's loop naturally does nothing, which is correct but worth a test case rather than an assumption.
An algorithm you rely on runs in O(n^2) time over a dataset that keeps growing, but your target device only has 32KB of RAM. How would you rework it to fit, and what would guide your choice of approach?
Sample Answer
Framing
This bundles two separate problems: an unbounded RAM ceiling (32 KB won't hold the whole growing dataset indefinitely) and an unbounded time cost (O(n^2) work growing with n). They need different fixes, but on a constrained device they interact, a fix for one alone can still fail on the other.
If the O(n^2) shape comes from all-pairs comparison
Naive duplicate detection or a naive nearest-neighbor scan comparing every element to every other element is the classic source of O(n^2). The standard time fix is a better algorithm for the same problem: sort once (O(n log n)) and compare only adjacent elements, or use a hash-based approach for exact matches (O(n) average), whichever matches what's actually being computed.
If holding the full dataset is what's actually blowing the 32 KB budget
Stop assuming full materialization is possible at all. Process in a streaming or windowed fashion, keeping only a bounded summary or a bounded window of recent elements (a fixed-size ring buffer) rather than the whole growing set. Some algorithms fundamentally need to see all pairs across the entire unbounded history, exact duplicate detection forever, for instance, and if that genuinely can't fit in 32 KB, the honest move is redefining the problem in terms of a bounded window ("duplicates within the last N items"), a real product trade-off to surface explicitly, not something to silently approximate.
Approximate structures as a middle ground
If exact correctness over the full growing set isn't strictly required, a fixed-memory probabilistic structure, a Bloom filter for approximate membership or duplicate checks, gives bounded RAM regardless of how large the dataset grows, at the cost of a known false-positive rate. This directly targets the "dataset keeps growing but RAM doesn't" mismatch in a way plain algorithm-swapping doesn't.
External storage as a last resort
If the device has flash beyond the 32 KB of RAM, spill the working set there and read back only what's needed for each step, a merge-sort-style external algorithm, trading I/O time (flash latency and write endurance) for RAM. Whether this is viable depends on flash wear characteristics and whether the access pattern is sequential enough to suit flash's block-oriented nature.
What guides the choice
The actual required correctness semantics, does the answer really need the full unbounded history, or is a recent window acceptable, how tolerant the application is of approximation (a monitoring or dedup use case may tolerate a Bloom filter's false positives, a billing or safety-critical one may not), and whether flash or external storage is even available to trade against RAM, on the smallest MCUs it may not be.
Why do embedded developers often use fixed-point arithmetic instead of floating point on resource-constrained MCUs, and how do you actually work with it (representation, scaling, rounding, overflow)? Walk through a simple example where fixed-point clearly wins over software floating point.
Sample Answer
Definition
Fixed-point representation stores a real number as an integer scaled by an implicit, fixed factor, multiply the real value by 2^n and store the integer result, instead of floating point, which stores a separate exponent so the decimal point can "float."
Why embedded developers use it
Most small MCUs (microcontroller units, the chip running this firmware), especially Cortex-M0/M0+ class and many low-cost 8/16-bit parts, have no hardware FPU (floating-point unit). Floating-point operations there are emulated in software, costing many times more CPU cycles and code (flash) size than an equivalent integer operation. Even on MCUs with an FPU, fixed-point can still win where bit-exact, deterministic results matter, since float rounding behavior can subtly differ across compilers and optimization levels.
Representation, scaling, rounding, overflow
- Representation: a Qm.n format packs m integer bits and n fractional bits into a normal integer type. Q8.8 stores a 16-bit signed value where the low 8 bits represent the fraction, so real value = raw integer / 2^n.
- Scaling: converting to fixed-point is
raw = round(value * 2^n); converting back isvalue = raw / 2^n. - Multiplication needs rescaling: multiplying two Qn numbers produces a raw product with 2n fractional bits, so you must shift right by n afterward to get back to the original format, and the intermediate product typically needs a wider type (int32 for two int16 Q8.8 operands) to avoid overflow before the shift.
- Rounding: truncating by shifting always rounds toward zero or negative infinity rather than to nearest, a bias that accumulates over many operations. Adding a rounding constant before the shift,
(product + (1 << (n-1))) >> n, rounds to nearest instead. - Overflow: the representable magnitude and precision are both hard limits fixed at compile time, unlike float, which trades precision for range dynamically. An intermediate product that overflows wraps around silently, with no exception, unlike a float overflowing to infinity, which is at least detectable.
Worked example
raw_product=⌊2naraw⋅braw⌋
Intuition: multiplying two scaled integers doubles the scale factor, so you divide back out by 2^n to land back in the original Qn format. In C this division by a power of two is written as a right shift, (a_raw * b_raw) >> n, one instruction instead of a real divide.
Using Q8.8 (scale factor 256): 3.5 encodes as round(3.5256) = 896, and 2.25 encodes as round(2.25256) = 576. Their raw product is 896576 = 516096 (needs a 32-bit intermediate, it doesn't fit in 16 bits). Rescaling: 516096 >> 8 = 2016. Decoding: 2016/256 = 7.875, matching the true product 3.52.25 = 7.875.
Where it clearly wins
That multiply, on an FPU-less MCU, is one 16x16-to-32 integer multiply and one shift, a handful of cycles. The floating-point equivalent on that same core is typically a software-emulated library call costing many times more cycles and considerably more flash space. For a control loop running at a fixed tick rate, say a PID controller (a common feedback-control loop that continuously corrects toward a target value) ticking every 1 ms, that emulation cost can be the difference between meeting the deadline and missing it.
Unlock Full Question Bank
Get access to all 36 Performance Optimization for Constrained Devices interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.