Sub topic 2
Measure First: Profiling Stages and Throughput
Assume you know basic Python, NumPy arrays, image tensors, and PyTorch Dataset and DataLoader. This chapter focuses on measurement. It does not yet optimise decoding, resizing, or batching.
Where Time Goes
An image input pipeline usually performs these stages:
- Read compressed bytes from storage.
- Decode bytes into pixels.
- Resize or crop the image.
- Assemble images into a batch.
- Copy the batch to the accelerator.
- Run model computation.
The slowest stage is the bottleneck, the stage that limits the pipeline's overall speed. Optimising another stage will not improve total throughput while the bottleneck remains unchanged.
Measure Per-Stage Time
Measure more than total time. Separate reading, decoding, and resizing so you can see which operation deserves attention. The following example uses a small list of image paths and reports average milliseconds per image.
import io
import time
from pathlib import Path
from PIL import Image
def time_stages(paths, size=(224, 224)):
read_time = decode_time = resize_time = 0.0
for path in paths:
start = time.perf_counter()
data = Path(path).read_bytes()
after_read = time.perf_counter()
image = Image.open(io.BytesIO(data)).convert("RGB")
after_decode = time.perf_counter()
image.resize(size, Image.Resampling.BILINEAR)
after_resize = time.perf_counter()
read_time += after_read - start
decode_time += after_decode - after_read
resize_time += after_resize - after_decode
count = len(paths)
if count == 0:
raise ValueError("paths must contain at least one image")
print(f"read: {read_time / count * 1000:.2f} ms/image")
print(f"decode: {decode_time / count * 1000:.2f} ms/image")
print(f"resize: {resize_time / count * 1000:.2f} ms/image")time.perf_counter() is appropriate for elapsed-time measurements because it uses a high-resolution monotonic clock. Run enough images to reduce noise. Include images from the real dataset because file size, dimensions, and format affect timing.
Measure Throughput Correctly
Throughput is the amount of work completed per unit of time. For training, the useful metric is often images per second:
\text{images per second} =
\frac{\text{number of images}}{\text{elapsed seconds}}Discard startup iterations when workers are warming up. Measure several batches and report the mean or median. Also record batch size, worker count, image shape, storage location, and whether the GPU is active.
| Measurement | What it reveals |
|---|---|
| Milliseconds per decode | CPU cost of turning compressed data into pixels |
| Batch time | Total input and model time for one batch |
| Images per second | End-to-end training or inference capacity |
| GPU utilisation | Whether the accelerator is waiting for input |
GPU operations are often asynchronous: Python may continue before the GPU finishes. Use torch.cuda.synchronize() around GPU timing measurements, or a profiler that understands GPU events. Otherwise, the measured time may describe only work submission, not completed work.
Common Measurement Errors
- Timing only the first batch includes worker startup and cache effects.
- Timing a single image exaggerates clock and filesystem noise.
- Comparing different datasets hides the real cause of a change.
- Measuring CPU code without checking GPU synchronisation gives misleading GPU times.
- Improving preprocessing time can reduce total time only if preprocessing is the bottleneck.
Exercise
A pipeline spends 8 ms reading, 20 ms decoding, 5 ms resizing, and 2 ms batching per image. Which stage should you investigate first, and why?
Show answer
Investigate decoding first because its 20 ms is the largest measured stage and is the most likely bottleneck.