Sub topic 7
Benchmarking with warmup and percentile latencies
This chapter assumes you have an exported resnet50.onnx with a dynamic batch axis and a working InferenceSession. You should also know the difference between latency and throughput, and be comfortable with NumPy. The GPU examples need an NVIDIA GPU with CUDA drivers. Every later chapter in this tutorial compares configurations, so you need a measurement method you can trust before you compare anything.
Why a single number misleads
A naive benchmark calls sess.run once, or averages a handful of calls, and reports "12 ms". That number can be wrong for three reasons.
- The first calls are slow. ONNX Runtime allocates memory, the CUDA provider initializes kernels and libraries, and the TensorRT provider may build an engine. These costs are paid once and have nothing to do with steady-state speed.
- The mean hides the tail. A service that answers in 10 ms most of the time but takes 80 ms on one request in a hundred feels slow to users. The mean barely moves, but the 99th percentile shows it.
- Other processes and clocks add noise. GPU clock changes, thermal limits, and other jobs on the machine cause run-to-run variation. One measurement cannot separate noise from a real change.
The fix is a fixed procedure: warm up, time many iterations individually, then report percentiles.
What percentiles mean
A percentile is the value below which a given share of samples falls. If p95 is 14 ms, then 95 out of 100 runs finished in 14 ms or less.
- p50 (median) is the typical run. It is robust to a few outliers.
- p95 and p99 describe the slow tail. Service-level targets are usually written against these.
- Max is dominated by one-off events. Look at it, but do not base decisions on it.
With 200 iterations, p99 rests on only the two slowest samples. For a stable p99, use at least 1000 iterations.
A complete benchmark function
The function below creates a session, warms it up, and times each call with time.perf_counter, a monotonic high-resolution clock. It returns percentiles instead of an average.
import time
import numpy as np
import onnxruntime as ort
def bench(sess, x, warmup=20, iters=200):
feed = {"input": x}
for _ in range(warmup):
sess.run(None, feed)
times = []
for _ in range(iters):
start = time.perf_counter()
sess.run(None, feed)
times.append((time.perf_counter() - start) * 1000.0)
p50, p95, p99 = np.percentile(times, [50, 95, 99])
return p50, p95, p99
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print("providers:", sess.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
print("p50/p95/p99 ms:", bench(sess, x))The print of get_providers() matters. If CUDA failed to load, ONNX Runtime silently falls back to the CPU, and you would otherwise benchmark the wrong device without knowing.
What this measures
Here x is a NumPy array on the host. Each sess.run call therefore includes copying the input to the GPU, running the graph, and copying the output back. This is the right number for an end-to-end service that receives host data. It is the wrong number if you want to compare kernels alone. The chapter on I/O binding shows how to remove the copies.
sess.run blocks until the outputs are ready, so the timer includes the GPU work. If you later time raw CUDA calls or bound outputs, you must synchronize the device before stopping the clock.
Measuring throughput across batch sizes
Throughput is the number of images processed per second. Compute it from the median latency of a batched run: batch / (p50 / 1000).
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
def run_times(sess, x, warmup=20, iters=200):
import time
feed = {"input": x}
for _ in range(warmup):
sess.run(None, feed)
out = []
for _ in range(iters):
t = time.perf_counter()
sess.run(None, feed)
out.append((time.perf_counter() - t) * 1000.0)
return np.array(out)
for batch in (1, 4, 8, 16, 32):
x = np.random.rand(batch, 3, 224, 224).astype(np.float32)
t = run_times(sess, x)
p50, p99 = np.percentile(t, [50, 99])
print(f"batch={batch:3d} p50={p50:7.2f} ms p99={p99:7.2f} ms "
f"throughput={batch / (p50 / 1000.0):8.1f} img/s")Expect latency to rise with batch size while throughput rises and then flattens once the GPU is saturated. If your service has a latency budget, choose the largest batch whose p99 still fits in it.
Timing GPU-resident tensors
When you use I/O binding, run_with_iobinding may return before the GPU has finished. Synchronize before reading the clock.
import time
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
x = np.random.rand(8, 3, 224, 224).astype(np.float32)
x_gpu = ort.OrtValue.ortvalue_from_numpy(x, "cuda", 0)
io = sess.io_binding()
io.bind_ortvalue_input("input", x_gpu)
io.bind_output("logits", "cuda", 0)
for _ in range(20):
sess.run_with_iobinding(io)
io.synchronize_outputs()
times = []
for _ in range(200):
start = time.perf_counter()
sess.run_with_iobinding(io)
io.synchronize_outputs()
times.append((time.perf_counter() - start) * 1000.0)
print("p50/p95/p99 ms:", np.percentile(times, [50, 95, 99]))Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No warmup | First-call setup inflates the average and p99 | Discard 20 or more runs |
| Timing the session constructor with the runs | TensorRT engine builds can take minutes | Time construction separately |
| Reporting only the mean | Hides tail latency | Report p50, p95, and p99 |
| Too few iterations | Unstable p99 | Use 1000 or more for tail claims |
| Unsynchronized GPU timing | Clock stops before work finishes | Synchronize outputs before stopping the clock |
| Changing the input shape mid-run | May trigger new engine builds or allocations | Warm up each shape you plan to time |
| Comparing runs on different providers | Unfair comparison | Print `get_providers()` for every run |
Making comparisons fair
Follow these rules whenever you compare two configurations, such as CUDA against TensorRT or FP32 against FP16.
- Use the same input shape, batch size, and dtype.
- Run both on the same machine, back to back, with nothing else using the GPU.
- Warm up each configuration separately, including each batch size you test.
- Repeat the whole benchmark two or three times. If p50 varies by more than a few percent between repeats, the machine is too noisy to trust small differences.
- Record the settings: ONNX Runtime version, driver version, provider options, and GPU model.
Check numerical parity first. A faster configuration that produces different outputs is not a valid speedup.
Reporting results
Report a short line that someone else could reproduce: model, batch size, provider list, iterations, and the three percentiles. For example: "ResNet-50, batch 8, CUDA EP, 1000 iterations: p50 6.1 ms, p95 6.4 ms, p99 7.0 ms". A narrow gap between p50 and p99 means steady behavior. A wide gap means something intermittent is happening, such as memory allocation, clock changes, or another process, and you should investigate before optimizing further.
Exercise
A benchmark of 30 runs with no warmup reports a mean latency of 25 ms, but p50 is 9 ms. What is the likely cause, and how do you fix the benchmark?
Show answer
The first few runs include one-time setup such as memory allocation and kernel or engine initialization. A few slow samples raise the mean far above the median. Add 20 or more discarded warmup iterations, raise the timed iterations to 200 or more, and report p50, p95, and p99 instead of the mean.
Exercise
You time run_with_iobinding with bound GPU outputs and see latencies far below the CPU-copy version. Name two things you should check before believing the result.
Show answer
First, check that the device is synchronized (for example with io.synchronize_outputs()) before the timer stops, because the call can return before the GPU finishes. Second, check that the providers list actually contains the CUDA provider, so the run was not on the CPU or measuring a different configuration. Also confirm that outputs still match the reference model.