labcd · 2026-11-27 · 12 min

Compute Budgets and Latency Bounds for PID, MPC, and Neural Policies

Comparing PID, MPC, and reinforcement learning requires evaluating execution cycles, solver jitter, and memory limits across embedded silicon targets.

Block diagram of a hybrid real-time control architecture mapping fast inner loops to microcontrollers and predictive optimization to high-performance silicon

Academic robotics literature regularly pitches classic proportional-integral-derivative (PID) control, Model Predictive Control (MPC), and Reinforcement Learning (RL) as competing paradigms. Papers often showcase a single quadrotor or bipedal robot running an end-to-end learned policy or a non-linear MPC formulation, claiming victory based entirely on tracking error or sample efficiency. Yet in industrial mechatronics, aerospace testbenches, and commercial robotics labs, these methods run into a hard physical constraint: real-time embedded compute budgets.

Every control loop operates against an uncompromising clock. If an actuator loop requires a 1 kHz update rate, the entire control cycle, from analog-to-digital conversion and state estimation to control calculation and PWM register writes, must complete in under 1000 microseconds. If the calculation takes 1001 microseconds, the system misses its deadline. Depending on the plant dynamics, a missed deadline can cause actuator chatter, phase margin degradation, or catastrophic closed-loop instability.

For engineering managers, control system architects, and robotics researchers, selecting an algorithmic approach without profiling memory allocation, floating-point execution cycles, and solver determinism is a direct path to project failure. The real engineering decision is not about choosing one paradigm over the others. It is about understanding the exact compute cost of each method across microcontrollers, system-on-modules, and FPGA targets, and structuring hybrid architectures that guarantee plant stability when solvers run out of time.

The Hardware Target Spectrum

To evaluate control algorithms objectively, we must look at the physical compute targets deployed on dynamic machines.

+-------------------------------------------------------------------------+
|                        COMPUTE TARGET HIERARCHY                         |
+-------------------------------------------------------------------------+
|  Target Class   | Typical Hardware     | Clock Speed | Determinism      |
+-----------------+----------------------+-------------+------------------+
| Hard Real-Time  | STM32H7 (Cortex-M7)  | 480 MHz     | Cycle-exact      |
| Coprocessors    | AMD Kria K26 (FPGA)  | 250 MHz     | Sub-microsecond  |
| Edge Linux      | Jetson Orin Nano     | 1.5 GHz     | Millisecond, OS  |
|                 | Raspberry Pi CM4     | 1.5 GHz     | jitter dependent |
+-------------------------------------------------------------------------+

Bare-Metal Microcontrollers (ARM Cortex-M4 / Cortex-M7)

Microcontrollers like the STM32H7 series running at 480 MHz provide cycle-exact determinism. They feature single-cycle hardware floating-point units (FPUs) for single-precision arithmetic, tightly coupled memory (TCM) to eliminate cache-miss latency, and direct register access to motor timers. However, they are severely memory-constrained, typically offering between 512 KB and 2 MB of SRAM. Dynamic memory allocation (malloc) is forbidden in production firmware due to heap fragmentation risks. Every matrix operation must be statically allocated at compile time.

System-on-Modules with Embedded Linux (PREEMPT_RT / Jetson / Raspberry Pi CM4)

Multi-core application processors running Linux with real-time kernel patches offer massive raw computational power, multi-gigabyte LPDDR4 memory, and support for high-level matrix libraries like Eigen or CasADi. However, they lack true cycle determinism. Memory bus contention, shared L3 cache misses, context switches, and thermal throttling introduce execution jitter. A control calculation that averages 2 milliseconds may spike to 12 milliseconds when an operating system thread claims the memory bus.

FPGA and Heterogeneous SoCs (AMD Kria, Zynq UltraScale+)

Field-programmable gate arrays allow hardware-level parallel execution of matrix operations. Quadratic programming (QP) iterations or matrix inversions can be pipelined in hardware logic, executing in hundreds of nanoseconds. The trade-off is development complexity, high thermal dissipation, and long engineering cycles required to implement numerical algorithms in register-transfer level (RTL) or High-Level Synthesis (HLS) C++.

Algorithmic Compute Profiles

Evaluating PID, MPC, and neural network policies requires looking at the actual operations executed during each sample step.

Classic PID and Gain-Scheduled Cascades

A standard parallel PID implementation with derivative filtering and back-calculation anti-windup requires approximately 20 to 40 floating-point operations (FLOPs) per axis. On an ARM Cortex-M7 running at 480 MHz, a complete 3-axis PID update executes in less than 2 microseconds.

u[k] = Kp * e[k] + Ki * Ts * sum(e) + (Kd / (Tf + Ts)) * (e[k] - e[k-1])

The compute time is completely constant. There are no iterative loops, no convergence criteria, and zero memory allocations. The phase delay introduced by the calculation is virtually zero. However, PID cannot natively handle multi-variable coupling, state constraints, or physical actuator limits during dynamic maneuvers without ad-hoc clamping that compromises loop stability.

Model Predictive Control (Linear and Non-Linear)

MPC computes control actions by solving a constrained optimization problem over a future time horizon $N$ at every sample step. For a linear-quadratic formulation with state dimension $n$ and control input dimension $m$, the controller solves a Quadratic Program (QP):

$$\min_{U} \frac{1}{2} U^T H U + g^T U \quad \text{subject to} \quad A_{in} U \le b_{in}$$

The size of the decision variable vector is $N \times m$. For a 12-state, 4-input quadrotor with a horizon of $N = 20$, the optimizer must solve for 80 decision variables subject to hundreds of inequality constraints every single cycle.

Two main classes of numerical QP solvers are used in real-time control:

  1. Active-Set Methods (e.g., qpOASES): These solvers find the exact set of active constraints by iterating through working sets. When warm-started near the optimal solution, they can converge in 5 to 10 iterations. However, during aggressive transients or sudden disturbances, the number of active-set changes multiplies, causing execution time to spike unpredictably.
  2. First-Order Methods / ADMM (e.g., OSQP, ProxQP): The Alternating Direction Method of Multipliers executes inexpensive matrix-vector multiplications per iteration without requiring matrix inversions inside the loop. The iteration time is uniform, but the total number of iterations required to reach a specific duality gap varies based on condition numbers and disturbance magnitude.

On an STM32H7, solving a small QP ($n=6, m=2, N=10$) using statically allocated ADMM takes between 1.2 ms and 4.5 ms. On an embedded Linux board, a non-linear interior-point solver (such as Ipopt or acados running SQP) takes between 5 ms and 35 ms for complex multibody systems.

Learned Neural Policies (Reinforcement Learning)

Once trained in simulation via policy gradient methods or PPO, deploying an RL policy on hardware requires running a forward pass through a Multi-Layer Perceptron (MLP) or recurrent network.

An MLP with 3 hidden layers of 128 neurons each requires matrix-vector multiplications of size (Input $\times$ 128), (128 $\times$ 128), (128 $\times$ 128), and (128 $\times$ Output), interspersed with activation functions like ReLU or Tanh. This amounts to roughly 70,000 FLOPs.

On a modern Cortex-M7 with CMSIS-NN, this forward pass takes roughly 150 to 300 microseconds. On an embedded GPU or NPU, it executes in tens of microseconds. The execution time of an MLP forward pass is completely deterministic: there are no iterations, no convergence checks, and no matrix factorizations at runtime.

However, neural policies present a different, critical failure mode: out-of-distribution behavior. When the physical robot enters a state space region not covered adequately during training, the network produces arbitrary control outputs without any mathematical guarantee of constraint satisfaction or Lyapunov stability.

Measured Silicon Footprint Comparison

The following benchmark data illustrates typical computational profiles across common embedded control platforms based on published embedded solver benchmarks and real-time controller implementations.

+-----------------------------------------------------------------------------+
|              REPRESENTATIVE CONTROLLER EMBEDDED BENCHMARK                   |
+-----------------------------------------------------------------------------+
| Target Platform: STM32H743ZI (480 MHz Cortex-M7) vs Jetson Orin Nano 8GB     |
| Problem Setup: 12-State, 4-Input Kinodynamic Model (Quadrotor/Cart-Pole)     |
| Solvers: CMSIS-DSP (PID), OSQP (Linear MPC, N=15), CMSIS-NN (MLP 3x128)      |
+-----------------------------------------------------------------------------+
| Metric                   | PID Cascade     | Linear MPC      | RL Policy    |
+--------------------------+-----------------+-----------------+--------------+
| Memory Footprint (Flash) | < 8 KB          | 145 KB          | 220 KB       |
| Static RAM Allocation    | < 1 KB          | 48 KB           | 64 KB        |
| Execution Time (STM32)   | 1.8 us          | 2.8 ms to 8.4 ms| 280 us       |
| Execution Jitter (STM32) | +/- 0.1 us      | +/- 3.2 ms      | +/- 2.5 us   |
| Execution Time (Orin)    | < 0.5 us        | 0.4 ms to 1.8 ms| 35 us        |
| OS Jitter (PREEMPT_RT)   | +/- 15 us       | +/- 450 us      | +/- 25 us    |
| Constraint Handling      | Manual Clamping | Exact Physical  | Soft Penalty |
| Stability Guarantees     | Frequency Bounds| QP Convergence  | Empirical    |
+-----------------------------------------------------------------------------+

Note: Illustrative composite derived from standard open-source embedded optimization benchmarks (OSQP, acados) and ARM CMSIS profiling on representative 12-state mechatronic plants.

The Real-Time Dilemma: Determinism vs Constraint Handling

The core architectural trade-off comes down to two conflicting requirements:

  1. Actuator physics demand high-frequency, jitter-free execution to preserve phase margin and reject high-frequency load disturbances.
  2. Multi-body dynamics and safety limits demand predictive constraint handling, which requires numerical optimization that cannot guarantee constant execution time.
       FAST INNER LOOP                        SLOW OUTER LOOP
    (Hard RTOS, 1 kHz - 10 kHz)              (PREEMPT_RT, 20 Hz - 100 Hz)
+-------------------------------+       +---------------------------------+
|        PLANT ACTUATION        |       |      OPTIMAL TRAJECTORY         |
|                               |       |                                 |
|  +-------------------------+  |       |  +---------------------------+  |
|  | Current / Torque Loop   |  |       |  | Model Predictive Control  |  |
|  | (Deterministic PID)     |  |       |  | (State/Input Constraints) |  |
|  +-------------------------+  |       |  +---------------------------+  |
|               ^               |       |                |                |
|               | 1 kHz         |       |                | 50 Hz          |
|  +-------------------------+  | Setpt |                v                |
|  | Velocity / Rate Loop    |<---------+----------------+                |
|  | (Gain-Scheduled PID)    |  |       |                                 |
|  +-------------------------+  |       |                                 |
+-------------------------------+       +---------------------------------+

If you try to run an MPC algorithm directly at 1 kHz on a microcontroller to command motor phase voltages, the solver will inevitably miss deadlines during large disturbance steps when active constraints change rapidly. When an optimization solver is terminated early due to a hard real-time interrupt, the primal solution is often dynamically infeasible, leading to sudden control jumps and actuator saturation.

Conversely, if you run a simple PID loop at 50 Hz to match your compute budget, the phase lag introduced by the low sampling frequency will render high-gain stabilization impossible on dynamic, unstable systems.

The Deterministic Hybrid Cascade Architecture

The industry-standard solution for high-performance robotics is a structured hybrid cascade. Instead of treating PID, MPC, and neural policies as mutually exclusive, each is placed in the control hierarchy where its computational properties match the required physical bandwidth.

1. Hard Real-Time Inner Loop (1 kHz to 10 kHz)

  • Host: Bare-metal ARM Cortex-M or FPGA coprocessor.
  • Algorithm: Discrete-time PID with anti-windup, feedforward compensation, and notch filtering.
  • Role: Closes high-rate current, velocity, or joint rate loops. Tracks commanded setpoints, cancels back-EMF, and suppresses high-frequency structural resonances. Rejects load disturbances within the actuator bandwidth.
  • Determinism: Cycle-exact execution with zero reliance on dynamic memory.

2. Predictive Outer Loop (20 Hz to 100 Hz)

  • Host: Real-time Linux core or secondary microcontroller thread.
  • Algorithm: Linear or Non-Linear MPC.
  • Role: Generates dynamically feasible reference trajectories (positions, velocities, torques) over a multi-step horizon while respecting physical torque, voltage, and kinematic constraints.
  • Solver Management: Implements warm-starting and a hard iteration cap. If the solver hits its compute deadline, it terminates gracefully.

3. Handling Solver Timeouts and Feasibility Drops

When deploying MPC in the outer loop, real-time code must include an explicit fallback mechanism for solver failure. The recommended strategy uses a shifted horizon buffer:

Step 1: Outer MPC solves optimal trajectory: U* = [u_0, u_1, u_2, ..., u_N-1]
Step 2: Transmit U* to inner loop ring buffer.
Step 3: At next cycle, attempt to solve for new horizon.
Step 4: IF solver succeeds within timeout T_max:
            Update ring buffer with new U*.
        ELSE (solver timeout or numerical infeasibility):
            Execute shifted backup step: u_fallback = u_1 from previous solution.
            Flag warning and relax constraint tolerances for subsequent cycle.

Because MPC computes an optimal trajectory over an entire horizon $N$, the tail of the previous solution provides a dynamically consistent control action if the current solve cycle misses its deadline. As long as solver drops do not occur across multiple consecutive cycles, the plant remains stable.

Decision Framework: Selecting Your Control Strategy

To determine the right control architecture for a mechatronic project, evaluate your system against four engineering criteria:

+-------------------------------------------------------------------------+
|                        CONTROL SELECTION MATRIX                         |
+-------------------------------------------------------------------------+
| Criterion              | Pure PID Cascade | Hybrid MPC + PID | Pure RL  |
+------------------------+------------------+------------------+----------+
| Compute Budget         | < 5% Cortex-M4   | Linux / High-M7  | GPU/SoM  |
| Constraint Dominance   | Low (Post-clamp) | Critical (State) | Soft-only|
| Model Accuracy         | Low (Local fit)  | High (Grey-Box)  | Sim-only |
| Validation Requirement | Gain/Phase Margin| Proof of Bounds  | Empirical|
+-------------------------------------------------------------------------+

Use a Pure PID Cascade When:

  • The plant dynamics are decoupled or weakly coupled across axes.
  • Actuator limits are rarely reached during nominal operation.
  • Compute is restricted to low-cost microcontrollers (e.g., motor drive gates, low-power IoT actuators).
  • Stability certificates must be proven via classical frequency-domain gain and phase margins.

Use a Hybrid MPC-over-PID Cascade When:

  • State and actuator constraints dictate system performance (e.g., maximum torque, collision boundaries, thermal current limits).
  • Significant multi-variable cross-coupling exists (e.g., multi-rotor attitude-translational coupling, robotic manipulators).
  • Compute hardware supports at least a high-end microcontroller (STM32H7) or an embedded Linux module with real-time extensions.
  • An identified mathematical model of the plant is available.

Use Reinforcement Learning Policies When:

  • The plant dynamics involve complex, non-differentiable contact physics that cannot be modeled in closed-form equations (e.g., rough-terrain quadrupedal foot placement).
  • Compute hardware includes a dedicated edge inference engine (NPU/GPU).
  • The team has the infrastructure to validate the policy across extensive randomized simulation suites and wrap the neural output in hard deterministic safety limiters.

What This Means for LabCD

At LabCD (labcd.ai), our focus is on providing control engineers with receipts: rigorous validation evidence, exact plant identification, and robust tuning workflows that do not break when flashed to embedded targets.

Building modern mechatronic systems requires bridging the gap between mathematical optimization and real-time embedded execution. LabCD enables engineering teams to identify multi-variable plant dynamics, tune high-bandwidth inner loops for maximum disturbance rejection, and validate predictive MPC cascades against realistic execution latency and jitter models. Instead of hoping that a simulation policy survives contact with physical hardware, engineers get the verification tools needed to prove stability before writing a single register.

Actionable Implementation Checklist

Before finalizing your embedded control architecture, run through this verification checklist:

  1. Profile Worst-Case Execution Time (WCET): Measure solver compute time during large step disturbances, not just at steady-state operating points. Active-set solvers take the longest when constraints are actively switching.
  2. Eliminate Dynamic Memory Allocation: Ensure all matrix workspaces, solver variables, and message buffers are statically allocated in TCM or SRAM at compile time.
  3. Implement a Fallback Buffer: Never allow a solver timeout to result in zero output or an uninitialized memory read. Use shifted-horizon buffers or gain-scheduled PID fallback states.
  4. Audit Sensor and Driver Latency: Calculate the phase loss introduced by ADC sampling filters, SPI bus transmission, and PWM update schedules. Add this phase delay into your plant identification model before tuning outer-loop gains.
  5. Verify Margins at the Inner Loop: Ensure the inner PID loop maintains at least 6 dB gain margin and 45 degrees phase margin even when the outer predictive planner is disabled or non-responsive.

Sources

More LabCD Insight

Embedded ControlModel Predictive ControlPID TuningRobotics Compute