NEWAI chat: ask your fleet anything, in plain language. Chat with your fleet Read more →

Why your robot is slow: control-loop latency and jitter in production

How to measure control-loop rate, jitter and late iterations on a robot running a model, find the line that's slow, and structure loops that hold.

Illustration for "Why your robot is slow": an autonomous forklift, with the label "loop 18 Hz · target 30 Hz"

"The robot feels slow." I hear that sentence a lot. Sometimes it means cycle time went from 14 seconds to 17. Sometimes it means the arm hesitates before every grasp. Sometimes it means a motion that used to be smooth now has a small shake in it.

Almost every time, the cause is the control loop.

Control loops used to be boring in the good way. A fixed program read sensors, computed a command, wrote it, slept. Same work every iteration, same time every iteration. Now there is a learned model in the loop. It decides from what the cameras see, many times a second, and its compute time moves around: the first call is slow, a thermal throttle makes it slower, a bigger checkpoint makes it slower still. The model changes with every release and the robot is in a factory, not on your desk. A loop that held 30 Hz in the lab can quietly run at 22 on the floor, and the robot's behavior changes with it.

This post is about measuring that properly, finding the cause, and structuring loops so they hold up.

The short answer: Usually it's the control loop, not the model. Measure the achieved loop rate, p99 iteration time, jitter and the share of late iterations, then find the slow line with a stack sampler. The usual causes are blocking serial or camera reads, model time that moves around, garbage-collection pauses, logging inside the loop and other processes on the same cores.

Measure the loop, not the model

Most teams measure inference time. That's one part of the iteration. The robot cares about the whole iteration. Measure these per loop:

  • Achieved rate. Iterations per second, measured, not configured. If the code says hz=30 and the loop does 24, the robot is running at 24.
  • Iteration time, median and p99. The median tells you the normal cost. The p99 tells you what the robot feels on its bad iterations. Averages hide everything interesting.
  • Jitter. How much the period varies. I like p99 minus median of the period, in milliseconds. It's easy to reason about: "most iterations take 31 ms, the bad ones take 48".
  • Late iterations. The share of iterations that took longer than the target period. This is the number I'd watch most closely. A loop with a fine median and 12% late iterations is a loop with a stutter.
  • The split. Of each iteration, how much was the model, how much other models, how much everything else. This tells you where to look before you open a profiler.

Starting points for thresholds, to adjust for your robot:

  • Late iterations above 1-2%: worth a look.
  • Late iterations at 10% or more while the median is fine: you have a periodic stall. Something runs every few iterations and blocks.
  • The loop running at 1.5x its own period or more: it is slow, full stop. The robot is behaving differently from how it was tested.

Measure it correctly

Three mistakes I see in almost every hand-rolled loop timer:

  • Using wall-clock time. time.time() jumps when NTP corrects the clock. On a robot that just got network after an hour offline, that can be seconds. Use a monotonic clock (time.monotonic() or time.perf_counter() in Python).
  • Measuring only the work. If you time from "start of compute" to "end of compute", you miss the time spent waiting on the sensor read at the top of the loop. Measure start-of-iteration to start-of-next-iteration. That's the period the robot actually sees.
  • Sleeping for the period. sleep(1/30) after the work makes every iteration take work plus 33 ms. Sleep until the next deadline instead, and if you are already past it, don't sleep at all and count the iteration as late. If you are far past it, skip ahead rather than trying to catch up with a burst of fast iterations.

The usual suspects

When a loop is slow or jittery in production, it's almost always one of these.

  • Blocking serial reads. The most common one on arms built from smart servos. Reading eight encoders one by one over a half-duplex bus means eight request-response round trips, each with a timeout. One servo with a flaky connector that sometimes doesn't answer turns a 4 ms read into a 50 ms read. The loop isn't computing, it's waiting. Use bulk or sync reads where the protocol has them, set short timeouts, and count timeouts as their own metric.
  • Camera reads that wait for the next frame. Calling read() on a camera at the top of the loop often blocks until the next frame arrives. A camera at 30 fps can add up to 33 ms to any iteration, and at 15 fps in low light (many webcams drop frame rate when it gets dark) it can add up to 66. Grab frames in their own thread and have the loop take the latest one, with its timestamp.
  • Model time variance. The first inference after load is slow (allocation, kernel compilation, cuDNN autotuning). A Jetson or Pi that gets hot throttles its clocks. An implicit CPU-GPU sync (.item(), .cpu(), printing a tensor) stalls the loop until the GPU finishes. Warm the model up before the robot moves, watch device temperature next to inference time, and keep sync points to one per iteration.
  • Garbage-collection pauses. Python's collector runs when it decides to. A loop that allocates lots of small objects every iteration (dicts, lists of floats, new numpy arrays) triggers it often. The pause shows up as periodic late iterations with a fine median. Preallocate buffers, reuse arrays, and consider gc.freeze() after startup so the collector stops rescanning everything you loaded at boot.
  • Logging in the loop. A synchronous log line written to an SD card that is half worn out can take tens of milliseconds. Fine in the lab with an SSD. Not fine on the robot. Log from the loop to a queue, and write from another thread.
  • Other processes on the same cores. A package update, a log rotation, an indexing job, a second model. On a 4-core board, any of them can take the core your loop runs on. Pin the control process to its own cores, give it higher priority, and keep heavy maintenance out of working hours.
  • Threads fighting for the GIL. In Python, a busy background thread (image preprocessing, a websocket client) can delay the loop thread even on a multi-core machine. If a background job is CPU-heavy, put it in its own process.

Finding the line that's slow

You know the loop is slow. Now you need to know where. Adding timers around every block works, but it's slow to iterate on, especially on a robot you can't easily redeploy.

Stack sampling is better. A sampler looks at the loop thread's call stack many times a second and counts which function and line it's in. After a minute you get a ranking: "read_encoders (robot.py:40), waiting, 92% of the time the loop was slow". That one line tells you it's the serial bus, not the model, and not your code's math.

Two things to know about sampling in Python:

  • Mark waiting vs running. A thread stuck in a socket or serial read is waiting. A thread in numpy is running. They have different fixes. Good samplers tell them apart.
  • It sees long stretches better than short ones. A sampler in the same process needs the GIL to look at the stack, so it gets in when the loop releases the GIL or after a short switch interval. It sees a 40 ms blocking read clearly and under-counts many 1 ms bits of pure Python. That's fine for this job. A slowdown is usually one long thing, not many small things.

Out-of-process samplers like py-spy work the same way and are great on a bench. In production, you want the sampler already running when the slowdown happens, because by the time someone opens a terminal, it has usually stopped.

Structure loops so they hold

Here is how I'd structure a robot app with a model in it. This is opinionated, on purpose.

  • Never let the model block the motor loop. Split into two loops. A fast control loop (say 100-500 Hz, depending on your hardware) that reads joints, follows the current target and writes commands. A slower policy loop that runs the model and hands over new targets or action chunks. The control loop never waits for the model. If the policy is late, the control loop keeps following the last plan.
  • Give every action an age, and a limit. Each target carries the time of the observation it came from. If the newest target is older than a limit you choose (a few policy periods is a reasonable start), the control loop holds position or stops. A stale action is a decision made about a world that has changed.
  • Start the next inference early. With action chunks, begin computing the next chunk before the current one runs out. Otherwise the robot finishes the chunk and stands still waiting. Blend the seam between chunks so the transition is smooth.
  • No I/O you don't control in the loop. No network calls, no synchronous logging, no file writes, no camera read() that blocks. Everything goes through queues and threads that can be slow without slowing the loop.
  • Preallocate. Allocate buffers and tensors once. Reuse them. On a GPU, keep the input tensor on the device and copy into it.
  • Name the phases. Split each iteration into named phases (observe, infer, act) and time each one. When the loop slows, the phase that grew tells you where to look.
  • One loop, one thread, one target rate, written in code. Not "whatever rate it ends up at". If the target is explicit, you can measure against it and alert on it.

The slow failures: leaks, threads and hidden errors

Some timing problems take hours or days to show.

  • Memory leaks. A loop that leaks a few kilobytes per iteration at 30 Hz runs out of memory in days, not minutes. Track process memory over time and fit a trend. "Memory grew steadily for 30 minutes, out of memory in about 9 hours" is much more useful than an OOM kill at 3 a.m. Watch GPU memory too. Reloading a checkpoint without letting the old one go is a classic GPU leak.
  • Thread growth. A reconnect handler that starts a new thread every time the network drops, and never stops the old one. Thread count should be flat. If it climbs, something is leaking threads.
  • Hidden exceptions. This one is my favorite, because it looks like nothing. Somewhere there's a try: read_gripper() except TimeoutError: pass. It was written for the rare timeout. Now the gripper's cable is loose and it times out on every iteration. Each timeout costs the full timeout period. The loop slows down, nothing is logged, and nobody looks at the gripper. Count caught exceptions per place in the code, and flag a place that suddenly catches far more than it used to. Exceptions you catch all the time by design, like an empty queue, are normal and should be ignored.

Same code, different speed

One last thing. In a fleet, the most useful question is often "why is this robot slower than the others running the same code?" If eight arms run the loop at 30 Hz and one runs at 12, the problem is almost never the software. It's that robot's SD card, its USB hub, a servo with a bad connector, a fan that stopped and a board that throttles. Compare each robot's loop rate and jitter with its peers and with its own history. We wrote more about this in finding the robot that's different.

And loop timing is only one part of watching a policy. For what to check on the model's inputs and outputs, see how to monitor a robot policy in production.

How we do it at PhysicalFleet

When your Python app runs under pf run or imports physicalfleet, PhysicalFleet measures the loop around the model with no code changes: rate, median and p99 iteration time, jitter, late iterations, and the split between the model and the rest. When a loop slows down, a stack sampler running in the app names the function and line taking the time and whether it was waiting. It also watches memory and GPU memory trends with time until out of memory, thread growth, error log lines and exceptions the app catches. For an exact target and phases, pf.loop("control", hz=30) makes the loop explicit. More on the observability page.

If you have a timing problem that took weeks to find, I'd really like to hear about it.

Common questions

What is jitter in a robot control loop?

Jitter is how much the loop's period varies from one iteration to the next. A practical measure is the p99 of the period minus the median, in milliseconds: most iterations take 31 ms, the bad ones take 48. Watch it together with the share of late iterations, because a loop with a fine median and many late iterations has a stutter.

How do I measure control-loop rate correctly in Python?

Use a monotonic clock like time.monotonic() or time.perf_counter(), never time.time(), which jumps when NTP corrects the clock. Measure from the start of one iteration to the start of the next, so time spent waiting on sensor reads is included. Sleep until the next deadline instead of sleeping a fixed period after the work.

How do I stop Python garbage collection from causing latency spikes?

Allocate less inside the loop: preallocate buffers, reuse arrays and avoid creating many small objects every iteration. Calling gc.freeze() after startup stops the collector from rescanning everything you loaded at boot. GC pauses usually show up as periodic late iterations while the median looks fine.

Should the model run in the same loop as the motor control?

No. Split it into a fast control loop that follows the current target and writes commands, and a slower policy loop that runs the model and hands over new targets. The control loop never waits for the model. Give every target the time of the observation it came from, and hold position or stop if the newest one is too old.

How do I find which line of code is making my robot slow?

Use a stack sampler on the loop thread. It looks at which function and line the thread is in many times a second, and after a minute it ranks where the time went, including whether the thread was waiting or running. In production you want the sampler already running, because a slowdown has often stopped by the time someone logs in.

#control loop#latency#jitter#robot performance#Python#real-time
Eitan ChudnovskyCo-founder, PhysicalFleet

From the lab bench. To the entire fleet.

Connect your first machine in minutes, develop it in the lab and run your whole fleet in production from one place.

Free for up to 3 machines · Then pay as you go