Sub topic 9
Benchmarking Latency on the Real Device
This chapter assumes you can export a model to TensorFlow Lite or ONNX and know what quantization does. It covers how to measure inference speed on the phone or board you will ship on, and how to read the numbers. A desktop run tells you little about a phone. Different CPU cores, memory bandwidth, drivers, and thermal limits can change latency by an order of magnitude.
Why desktop numbers mislead
A laptop CPU can run a MobileNet in a few milliseconds. The same model on a phone may be much slower, or faster if an NPU takes over. Three things cause the gap:
- Heterogeneous cores. Many phone SoCs (systems on a chip) mix fast "big" cores with slow "little" cores. The operating system scheduler decides where your thread runs, so the same code can give different times from run to run.
- Different backends. The operator kernels, the GPU driver, and the NPU delegate on the device are not the ones on your desktop. A delegate may run only part of the graph, with the rest on the CPU.
- Dynamic clocks. Phones lower their clock speed when they get hot or when the battery is low. A benchmark that runs for two seconds measures a different device from one that runs for two minutes.
The rule is to measure on the target device, with the final model file, the final runtime version, and the final delegate settings.
What to measure
"Latency" can mean several things. Decide which one you report.
| Quantity | What it covers | When it matters |
|---|---|---|
| Model inference time | Only the interpreter or session call | Comparing models and delegates |
| End-to-end latency | Camera frame in, result on screen | User-perceived responsiveness |
| Cold start | Loading the model and first inference | App launch, first use of a feature |
| Steady-state latency | Repeated inference after warm-up | Live camera pipelines |
| Throughput (FPS) | Frames processed per second | Video and batch processing |
Report percentiles, not just the mean. The median (p50) describes the typical run. The 95th percentile (p95) describes the slow tail, which is what users notice as stutter. For a 30 FPS camera feed, each frame has about 33 ms. A model with a 20 ms median and a 60 ms p95 will still drop frames.
The benchmark loop
A reliable benchmark has the same shape every time.
Warm-up
The first few inferences are slow. The runtime allocates buffers, compiles GPU shaders, or builds an NPU graph. Caches are empty too. Discard at least 10 runs before timing. Record the first-run time separately as your cold-start figure, because users do experience it.
Clock and repetition
Use a monotonic clock such as time.perf_counter() in Python, System.nanoTime() on Android, or DispatchTime / ContinuousClock on iOS. Do not use wall-clock time, which can jump. Run at least 100 timed iterations so that the p95 is based on more than a handful of samples.
A Python benchmark for TensorFlow Lite
This script works on any device where Python and TensorFlow Lite run, such as a Raspberry Pi or a Linux board. It uses the quantized model from the export chapter.
import time
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite", num_threads=4)
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"])
for _ in range(10): # warm-up runs are excluded from timing
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
times = []
for _ in range(100):
start = time.perf_counter()
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
times.append((time.perf_counter() - start) * 1000)
print(f"median {np.median(times):.1f} ms, p95 {np.percentile(times, 95):.1f} ms")The input is all zeros. That is fine for timing a dense convolutional model, because the arithmetic cost does not depend on the pixel values. It is not fine for every model. Models with data-dependent steps, such as non-maximum suppression in a detector, take different time on empty and busy images. For those, time real frames.
The same idea in ONNX Runtime
The loop is identical. Only the session API changes. This example loads the model exported earlier with the input name input.
import time
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession(
"mobilenet_v3_small.onnx", providers=["CPUExecutionProvider"]
)
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
for _ in range(10):
session.run(None, {"input": x})
times = []
for _ in range(100):
start = time.perf_counter()
session.run(None, {"input": x})
times.append((time.perf_counter() - start) * 1000)
print(f"median {np.median(times):.1f} ms, p95 {np.percentile(times, 95):.1f} ms")To test an accelerator, change the providers list to one that exists on your device, such as ["NnapiExecutionProvider", "CPUExecutionProvider"] on Android builds that include it. Listing the CPU provider last gives a fallback for operators the accelerator cannot run. Check session.get_providers() to see what was actually registered.
Using the vendor benchmark tools
Python on a phone is rare. For Android, use the prebuilt command-line tools, which run native code without app overhead.
TensorFlow Lite ships benchmark_model. Push the binary and the model, then run it through adb:
adb push benchmark_model /data/local/tmp/
adb push mobilenet_v2_int8.tflite /data/local/tmp/
adb shell chmod +x /data/local/tmp/benchmark_model
adb shell /data/local/tmp/benchmark_model \
--graph=/data/local/tmp/mobilenet_v2_int8.tflite \
--num_threads=4 \
--warmup_runs=10 \
--num_runs=100 \
--use_gpu=trueIt prints initialization time, warm-up time, and inference statistics. It can also report which nodes were delegated and, with profiling enabled, the time per operator. Run it once per configuration: CPU with 1, 2, and 4 threads, then the GPU, then NNAPI. ONNX Runtime has a similar tool, onnxruntime_perf_test. Core ML models can be profiled in Xcode's performance report, and Instruments gives a finer view on iOS.
Controlling the measurement
Small differences in setup change results. Control these:
- Thread count. More threads help up to a point, then synchronization costs dominate. On big.LITTLE chips, 4 threads may land on slow cores. Test 1, 2, and 4.
- Device state. Keep the battery above about 50 percent, turn off battery saver, and close other apps. Let the phone cool between runs.
- Build type. Benchmark a release build. Debug builds, and apps with a debugger attached, can be much slower.
- Screen and sensors. In an end-to-end test, the camera, display, and other app work compete for the same memory bandwidth and thermal budget.
- Same inputs. Use the same input shape and, for data-dependent models, the same set of images each time.
Record the device model, OS version, runtime version, delegate, thread count, and model file hash with every result. Without them, a number cannot be reproduced or compared.
Steady state and thermal throttling
A short benchmark shows the best case. Real use, such as a camera feed running for ten minutes, heats the chip. Once it passes its thermal limit, the system reduces clock speed and your latency rises.
To catch this, run the timed loop for several minutes and log latency in windows, for example the median of every 100 runs. Plot the windows. A flat line means stable performance. A staircase upward means throttling. Report both the first-minute number and the number after the device has been hot. Design to the hot number if the feature runs continuously. The next chapters on power and thermal behavior cover mitigation.
Separating where the time goes
End-to-end latency is the sum of stages: capture, resize and normalize, inference, and postprocessing such as decoding boxes. Time each stage separately. It is common to find that inference takes 8 ms while a slow bitmap conversion takes 15 ms. Optimizing the model then gains nothing. Add a timer around each stage and log the percentiles for each one.
Per-operator profiles show which layers dominate. If a few operators run on the CPU while the rest run on the NPU, the data copies between them can cost more than the savings. That pattern points to an unsupported-operator problem.
Common mistakes
- Timing only one run. A single sample includes warm-up and noise.
- Reporting the mean only. Outliers hide in it, and tail latency is invisible.
- Benchmarking on a desktop emulator. Emulators do not reproduce the SoC, the delegates, or the thermal behavior.
- Comparing runs on different thermal states. The second configuration tested on a warm phone looks worse for no model-related reason.
- Leaving out data movement. Copying a bitmap into a tensor, or reading output from GPU memory, is part of the cost.
- Assuming a delegate is active. If the delegate failed to initialize, many runtimes silently use the CPU. Confirm from the logs or the benchmark tool output.
Exercises
Exercise
A model on a phone shows a median latency of 18 ms and a p95 of 70 ms over 100 runs. The app processes a 30 FPS camera stream. Is the model fast enough, and what would you check next?
Show answer
Not reliably. A 30 FPS stream gives about 33 ms per frame, and the p95 of 70 ms means roughly 1 in 20 frames takes longer than two frame periods, so frames will drop and the video will stutter. Next, check whether the slow runs come from warm-up, from scheduling on slow cores (try different thread counts), or from thermal throttling (log latency in windows over several minutes). Also check whether the stages around inference, such as preprocessing, add to the tail.
Exercise
You run benchmark_model with --use_gpu=true and the latency is identical to the CPU run. Give two possible explanations and one way to confirm each.
Show answer
First, the GPU delegate may have failed to initialize and the runtime fell back to the CPU. Confirm from the tool output or logcat, which show whether the delegate was applied. Second, the delegate may be active but the graph may be dominated by operators it cannot run, which stay on the CPU. Confirm from the per-node delegation report or the operator profile, which lists the nodes handled by the delegate.