Reliable MLX timing: lazy evaluation, warm-up and sync

Reliable MLX timing: lazy evaluation, warm-up and sync

Reliable MLX timing: lazy evaluation, warm-up and sync

The same MLX code runs slowly the first time, then so quickly on the second run that it seems to do no computation at all. Move it to a remote node, and the time reported by the script is shorter than the time you actually spend waiting. Before comparing machines, check what you are measuring: you may be timing only the construction of the computation graph, or letting unfinished device work from one experiment spill into the next. The small experiment below establishes a sound timing method before applying it to model inference.

Define exactly what the timing includes

MLX uses lazy evaluation. Writing a matrix multiplication expression does not mean the result has been computed. mx.eval triggers evaluation of the result, while mx.synchronize waits for device work to finish. Where you place these calls determines what your numbers mean.

This experiment measures wall-clock time from creating the multiplication expression to completion of the result. It includes submission and synchronization overhead and does not claim to measure pure GPU kernel time. Input creation, random number generation, and warm-up all take place outside the sampling interval. Synchronize before starting so earlier work cannot leak into the measurement; evaluate and synchronize before stopping so the timer does not end too soon.

Every performance figure needs a defined measurement boundary. A reported duration that does not state whether it includes loading, warm-up, and synchronization cannot be compared directly with other results.

Both initial loading and steady-state execution are worth recording, but they belong in separate experiments. Do not quietly discard the first slow sample and still call the result end-to-end latency.

Run a minimal experiment in an isolated environment

On the cloud Mac, prepare a working native arm64 Python 3 installation. Check the interpreter architecture first, then create a dedicated virtual environment. The dependency installation below is for the initial setup. Once the environment works, save its package versions and use that same environment record for subsequent comparisons.

uname -m
python3 -c 'import platform; print(platform.machine())'
mkdir -p "$HOME/mlx-timing"
cd "$HOME/mlx-timing"
python3 -m venv .venv
.venv/bin/python -m pip install mlx
.venv/bin/python -m pip freeze > requirements-observed.txt
sw_vers > system-version.txt

Both architecture checks should print arm64. Save the following as bench.py. It uses a fixed matrix size of 1024 and float32, with five warm-up runs followed by twenty measured runs. These are simply experiment parameters, not performance claims for any machine.

import json
import platform
import statistics
import time
from importlib.metadata import version

import mlx.core as mx

mx.set_default_device(mx.gpu)
mx.random.seed(7)

size = 1024
warmups = 5
repeats = 20
a = mx.random.normal((size, size)).astype(mx.float32)
b = mx.random.normal((size, size)).astype(mx.float32)
mx.eval(a, b)
mx.synchronize()

def run_once():
    result = a @ b
    mx.eval(result)
    mx.synchronize()
    return result

for _ in range(warmups):
    run_once()

samples = []
for _ in range(repeats):
    mx.synchronize()
    started = time.perf_counter_ns()
    result = run_once()
    elapsed = time.perf_counter_ns() - started
    samples.append(elapsed / 1_000_000)

finite = bool(mx.all(mx.isfinite(result)).item())
if not finite:
    raise RuntimeError("Non-finite result")

report = {
    "python": platform.python_version(),
    "macos": platform.mac_ver()[0],
    "machine": platform.machine(),
    "mlx": version("mlx"),
    "device": "gpu",
    "dtype": "float32",
    "shape": [size, size],
    "warmups": warmups,
    "repeats": repeats,
    "finite": finite,
    "samples_ms": samples,
    "median_ms": statistics.median(samples),
    "min_ms": min(samples),
    "max_ms": max(samples)
}
print(json.dumps(report, indent=2))

Save the results to files rather than copying only the fastest figure from the terminal:

.venv/bin/python bench.py > run-01.json
.venv/bin/python bench.py > run-02.json
.venv/bin/python bench.py > run-03.json

The script creates a new multiplication expression on each run instead of repeatedly evaluating the same array whose result is already available. The final check for finite values only rules out obvious problems; it is not a validation of numerical accuracy.

Read the samples, not the fastest result as a promise

First check that all three reports use the same versions, shape, data type, and device. Then compare the medians and raw samples. The minimum shows only that one execution was faster; the maximum can alert you to variability worth investigating. Twenty samples are not enough to make a reliable high-percentile latency commitment.

Change only one variable at a time

Keep all other parameters unchanged when modifying the matrix size. If you change precision, create a separate report rather than mixing float16 and float32 into the same trend. Different matrix sizes can also take different computational paths, so execution time cannot simply be extrapolated from the ratio of element counts.

Before running the experiment, stop other inference, fine-tuning, and batch jobs you have started. If an entire run becomes slower, save the current state and task list before testing again. Do not try to “wash out” the problem by increasing warm-up runs indefinitely. If the median continues to change as you add warm-up runs, record that behavior rather than declaring the system stable.

Apply the same boundaries to real inference

The matrix experiment checks the measuring tool; its results cannot be converted into model generation throughput in tokens per second. For real inference, distinguish at least three measurements: process start to model readiness, request submission to availability of the first output token, and step-by-step generation after the first token.

Keep the model files, tokenizer, input token count, output limit, sampling parameters, and concurrency fixed. State explicitly whether the prefill cache is reused. Repeated requests with the same prompt may hit the cache and can no longer be described as fully independent cold requests.

Step-by-step generation usually depends on the preceding step's result. The time taken to build the computation graph for an entire generation expression is therefore not the total decoding time. Check the interface you are using to determine when tokens actually become available, and stop timing at a consistently defined completion boundary. If network transfer is included, label the result as client-observed latency rather than mixing it with timing measured inside the node.

Finish with an experiment record

For each run, retain the code version, dependency list, system version, experiment parameters, and raw JSON. When a model is involved, also record the weight identifier, input samples, and cache policy. For private prompts, a controlled sample identifier is sufficient; the prompt itself need not appear in public logs.

Check each item before accepting the results:

End the report with a conclusion that someone else can repeat: what was measured, what was excluded, and which variables remain uncontrolled. Make the measurement reproducible before debating whether an optimization works. That is more useful than an impressive speed figure no one can explain.

Frequently asked questions

Does timing an MLX expression measure completed computation?

Not reliably. Lazy evaluation may only build a graph. Evaluate the result with mx.eval and synchronize before stopping the timer; also drain earlier work before starting.

Can matrix multiplication timings predict tokens per second?

No. They validate the timing harness, not model throughput. Tokenization, prompt prefill, caches and decoding require a separate benchmark with fixed inputs and output length.

Rent for a Day to Test Your Model

VPSMain offers dedicated physical Mac mini servers—not virtual machines—from $19.6/day. Rent by the day, week, month, or quarter, with same-day setup. Choose unified memory based on quantized model weights, KV cache, and system overhead.