Sub topic 9
Benchmarking Latency on the Real Device
This chapter assumes you understand tensors, model inference, and basic Python. You should also know how your model is exported and which runtime or hardware delegate it uses. The goal is to measure the time users actually experience, not just the time reported on a development computer.
Define What Latency Means
Latency is the time needed to process one input. For a camera model, the complete path often includes:
- Capturing a camera frame.
- Resizing and normalizing the image.
- Copying data into the runtime.
- Running the model.
- Copying the output back.
- Selecting or drawing the result.
Measure these stages separately when possible. A model may take 12 milliseconds for inference but 25 milliseconds after image conversion and output processing.
Throughput is the number of inputs processed per second. A real-time application may care about both values. For example, a video application that processes one frame every 50 milliseconds has a maximum throughput of 20 frames per second.
| Measurement | Meaning | Useful for |
|---|---|---|
| Median latency | Typical time for one inference | Normal user experience |
| p95 latency | Time that 95% of runs finish within | Jitter and responsiveness |
| Throughput | Inputs processed per second | Video and batch workloads |
| Peak memory | Highest memory used during a run | Device compatibility |
Use a Repeatable Procedure
Run the benchmark on the target device, with the same model, input shape, data type, thread count, and delegate that the application will use. A desktop result cannot predict phone performance reliably.
First, warm up the runtime. The first calls may include memory allocation, kernel selection, or delegate initialization. Exclude them from the measured sample.
Then collect many measurements. One measurement is not useful because operating-system scheduling, background applications, and garbage collection introduce noise. Report the median and a high percentile such as p95.
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()
input_info = interpreter.get_input_details()[0]
output_info = interpreter.get_output_details()[0]
image = np.zeros(input_info["shape"], dtype=input_info["dtype"])
def run_once():
interpreter.set_tensor(input_info["index"], image)
interpreter.invoke()
return interpreter.get_tensor(output_info["index"])
for _ in range(10):
run_once()
latencies_ms = []
for _ in range(100):
start = time.perf_counter()
run_once()
latencies_ms.append((time.perf_counter() - start) * 1000)
print(f"median: {np.median(latencies_ms):.1f} ms")
print(f"p95: {np.percentile(latencies_ms, 95):.1f} ms")
print(f"throughput: {1000 / np.mean(latencies_ms):.1f} inferences/s")This example measures only the interpreter call and tensor access. To measure the application path, include preprocessing and postprocessing in separate timers. Keep the input fixed while comparing runtime settings so that the comparison is fair.
Account for Thermal Throttling
A short benchmark may measure the device's fastest state. During sustained use, the device can heat up and reduce CPU or GPU frequency. This behavior is called thermal throttling.
Run a short test to check startup latency, then run a longer test for sustained performance. Record latency in time windows, such as every 50 or 100 inferences. A rising p95 value indicates that the device is no longer maintaining its initial speed.
Compare Settings Carefully
Change one variable at a time. For example, compare four CPU threads with two threads before changing the delegate. A faster configuration is not automatically better if it uses more battery or causes throttling.
Test at least these cases when they are available:
- CPU with the intended thread count.
- GPU or NPU delegate.
- The exact input resolution used by the app.
- Cold startup and warmed-up execution.
- Short and sustained workloads.
Validate the Result
A benchmark is useful only when it supports a decision. Set a latency target before testing, such as a median below 30 milliseconds and p95 below 45 milliseconds. Also check that the output remains correct. A delegate that silently falls back to the CPU may produce valid predictions while missing the expected speed target.
Exercise
Your median latency is 18 ms, but p95 latency is 75 ms after a five-minute camera test. What should you investigate first?
Show answer
Check for thermal throttling, background activity, garbage collection, and intermittent CPU fallback. Compare latency over time and inspect runtime logs rather than relying on the median alone.