Sub topic 3
Measure first: build a cost and latency baseline
This chapter assumes you can call an LLM API from Python and read its response, including the token counts the provider reports. It also assumes you know what a streamed response is and have a rough idea of how tokens are priced. The chapter builds a small measurement harness and uses it to produce a baseline you can compare against after every later change.
Why a baseline comes before any optimization
Most cost and latency work fails in one of two ways. You optimize something that was never the bottleneck, or you change something and cannot tell whether it helped. A baseline prevents both. It is a set of numbers, taken from realistic traffic, that describes how your application behaves today.
A baseline answers three questions:
- Which requests cost the most, and why? Input tokens, output tokens, or sheer volume?
- How long do users wait for the first visible output, and how long for the full answer?
- How much do those numbers vary from one request to the next?
Every later technique in this tutorial, such as trimming prompts, caching, or switching models, is judged against these numbers.
What to record for each request
Log one record per request, with enough fields to slice the data later. Record only what you can measure directly, and compute everything else from those fields.
| Field | Source | Why it matters |
|---|---|---|
| `route` | Your code | Names the feature or prompt template, so you can compare features |
| `model` | Your code | Prices and speeds differ by model |
| `input_tokens`, `output_tokens` | Provider's usage report | Drive cost. Use the reported values, not your own estimates |
| `ttft_s` | Stopwatch around the stream | Time to first token, the wait before anything appears |
| `total_s` | Stopwatch | Time until the response is complete |
| `cost_usd` | Computed from tokens and prices | Lets you sum and compare |
| `error` | Exception type, or none | Failed and retried requests cost time, and sometimes money |
Token counts from the provider are the source of truth. A local tokenizer such as tiktoken is useful for estimating a request before you send it, as in the cost estimate from the first chapter. Providers may add formatting or system tokens that a local count misses, so the billed numbers come from the usage report.
Measuring time to first token and total time
Latency has two parts you need to separate. Time to first token (TTFT) covers the wait in the queue and the prefill, which is the model reading your whole prompt. Generation time is the rest, spent producing output tokens one after another. A long prompt mostly raises TTFT. A long answer mostly raises generation time. Measuring both tells you which one to attack.
To get TTFT you must stream. Without streaming you see only the total. The wrapper below records both from any stream and also collects usage and errors.
import json
import math
import random
import time
# Placeholder prices in USD per million tokens. Replace with your provider's current prices.
PRICE_PER_MTOK = {"input": 1.00, "output": 4.00}
def cost_usd(input_tokens, output_tokens):
return (
input_tokens * PRICE_PER_MTOK["input"]
+ output_tokens * PRICE_PER_MTOK["output"]
) / 1_000_000
def fake_stream(prompt):
"""Stand-in for a real streaming API call. Yields ("text", str) then ("usage", dict)."""
if random.random() < 0.05:
raise RuntimeError("simulated provider error")
time.sleep(random.uniform(0.05, 0.2)) # queue and prefill
n_out = random.randint(20, 60)
for _ in range(n_out):
time.sleep(0.002) # one decoding step
yield ("text", "tok ")
yield ("usage", {"input_tokens": len(prompt.split()) * 2, "output_tokens": n_out})
def measure_request(route, model, prompt, stream_fn):
start = time.perf_counter()
ttft = None
usage = None
error = None
try:
for kind, value in stream_fn(prompt):
if kind == "text" and ttft is None:
ttft = time.perf_counter() - start
elif kind == "usage":
usage = value
except Exception as exc:
error = type(exc).__name__
total = time.perf_counter() - start
in_tok = usage["input_tokens"] if usage else None
out_tok = usage["output_tokens"] if usage else None
return {
"route": route,
"model": model,
"input_tokens": in_tok,
"output_tokens": out_tok,
"ttft_s": ttft,
"total_s": total,
"cost_usd": cost_usd(in_tok, out_tok) if usage else None,
"error": error,
}
def percentile(values, p):
"""Nearest-rank percentile. Requires a non-empty list."""
ordered = sorted(values)
rank = max(0, math.ceil(p / 100 * len(ordered)) - 1)
return ordered[rank]
def summarize(records):
ok = [r for r in records if r["error"] is None and r["ttft_s"] is not None]
if not ok:
return {"n": len(records), "error_rate": 1.0}
return {
"n": len(records),
"error_rate": 1 - len(ok) / len(records),
"ttft_p50": percentile([r["ttft_s"] for r in ok], 50),
"ttft_p95": percentile([r["ttft_s"] for r in ok], 95),
"total_p50": percentile([r["total_s"] for r in ok], 50),
"total_p95": percentile([r["total_s"] for r in ok], 95),
"mean_cost_usd": sum(r["cost_usd"] for r in ok) / len(ok),
"sum_cost_usd": sum(r["cost_usd"] for r in ok),
}
if __name__ == "__main__":
prompts = {
"summarize": "Summarize this paragraph in two sentences. " * 20,
"classify": "Label this ticket as billing, bug, or other.",
}
records = []
with open("baseline.jsonl", "w", encoding="utf-8") as f:
for _ in range(20):
for route, prompt in prompts.items():
rec = measure_request(route, "model-a", prompt, fake_stream)
records.append(rec)
f.write(json.dumps(rec) + "\n")
for route in prompts:
subset = [r for r in records if r["route"] == route]
print(route, summarize(subset))Replace fake_stream with a function that wraps your real client and yields the same two kinds of events. The harness does not change. The jsonl file gives you one line per request, which is easy to append to, load into a dataframe, or compare across runs.
Report percentiles, not averages
Latency distributions have a long tail. Most requests finish quickly, and a few take several times longer because of queueing, long outputs, or retries. An average hides that tail and a single slow request can skew it.
- p50 (the median) is the typical experience.
- p95 is the value that 95% of requests beat. It shows what your slower users see.
- p99 matters at high volume, but you need hundreds of samples before it means anything.
Report cost the same way when outputs vary a lot. The mean cost per request tells you the budget, and the p95 cost shows whether a few runaway outputs dominate spending.
Slice by route before drawing conclusions
A single overall number is rarely useful. A classifier with short inputs and one-word outputs and a summarizer with long inputs and long outputs behave very differently. If you merge them, the result describes neither. Always group by at least route and model, and by anything else that plausibly changes behavior, such as input length bucket.
The slices also tell you where to look first. Multiply each route's mean cost by its request count. The route with the largest total is usually the best place to start, even if its per-request cost is unremarkable.
Edge cases that distort a baseline
- Unrepresentative traffic. Measuring with a few hand-written prompts gives numbers that do not match production. Sample real requests, with sensitive data removed, or build a set with the same length distribution.
- Too few samples. Twenty requests cannot support a p95. Aim for at least a few hundred per route for stable tail numbers, and treat smaller runs as rough.
- Time-of-day variance. Shared provider capacity changes through the day. Run the baseline over more than one period, or note when it was taken.
- Cold starts and warm-up. The first requests after idle time can be slower. Discard a handful of warm-up requests, or report them separately.
- Cache hits. If a provider cache or your own cache is active, repeated identical prompts look faster and cheaper than new traffic. Measure with caching off, or tag each record with a hit flag.
- Retries and failures. A request that failed and was retried has a longer wall-clock time and may bill for the failed attempt. Record the error and attempt count instead of dropping them, which is why
summarizereportserror_rateseparately. - Hidden output. Some models spend tokens on internal reasoning that is billed as output but not shown. If your
output_tokensis far larger than the visible text suggests, check the provider's usage fields. - Sampling settings. Temperature and maximum output length change output length. Hold them fixed between runs, or your comparison measures the settings and not your change.
Using the baseline
Keep the baseline file under version control, with the date, model name, prices, and sampling settings in a note beside it. Prices change, so store token counts and recompute cost when needed. When you try an optimization, rerun the same harness on the same inputs and compare p50 and p95 TTFT, p50 and p95 total time, mean cost, and error rate. A change that improves one number while worsening another is a trade-off. The next chapter adds a quality check so you can see that third side of the trade.
Exercise
Your baseline shows a summarization route with p50 TTFT of 0.4 s but p50 total time of 9 s, and an average of 700 output tokens. A teammate proposes shortening the system prompt by 200 tokens to fix the slow responses. Based on the measurements, will that help much, and what would you measure or change instead?
Show answer
Probably not much. TTFT is already low, so prefill (which a shorter prompt speeds up) is not the main delay. Most of the 9 s is generation time for about 700 output tokens. The better levers are limiting or shaping the output length, and streaming so users see text early. A shorter prompt will still save a little cost, since input tokens are billed, so measure its cost effect separately. Confirm with p95 values and by checking how output length varies across requests.