Sub topic 3
Measure first: build a cost and latency baseline
This chapter assumes you can call an LLM API from Python, know what tokens are, and have read the earlier chapters on token pricing and latency. Before you change a prompt or switch models, record how the system behaves today. Without a baseline you cannot tell whether a change helped.
What to record
Log one row per request. These fields cover most needs:
- Input tokens and output tokens, taken from the API's usage report, not your own estimate.
- Time to first token (TTFT) and total time.
- Model name and a prompt version label.
- Computed cost.
- Status: success, error, or retry.
Provider-reported token counts are authoritative. Local counts from a tokenizer such as tiktoken are good for planning but can differ by a few percent, and chat formatting adds tokens you do not see.
Time a request
The time_stream helper wraps any iterable of streamed chunks. It records TTFT, which reflects queueing and prefill, and total time, which adds decoding.
import time
def time_stream(chunks):
"""Measure time to first chunk and total time for any iterable of streamed chunks."""
start = time.perf_counter()
first = None
count = 0
for _ in chunks:
if first is None:
first = time.perf_counter() - start
count += 1
total = time.perf_counter() - start
return {"ttft_s": first, "total_s": total, "chunks": count}Call it on the stream you get from your client. If the stream is empty, ttft_s stays None, so handle that case when you aggregate.
Turn counts into cost
Input and output tokens have separate prices, so compute them separately. The prices below are placeholders. Replace them with your provider's current prices.
PRICE_PER_MTOK = {"input": 1.00, "output": 4.00}
def request_cost(input_tokens: int, output_tokens: int) -> float:
return (
input_tokens * PRICE_PER_MTOK["input"]
+ output_tokens * PRICE_PER_MTOK["output"]
) / 1_000_000Summarize with percentiles
Averages hide slow requests. Report the median (p50) and the tail (p95) for latency, and report mean and p95 for tokens. Collect a few hundred requests from realistic traffic, not hand-picked examples.
import statistics
def summarize(rows):
def pct(values, q):
values = sorted(values)
return values[min(len(values) - 1, int(q * len(values)))]
ttft = [r["ttft_s"] for r in rows if r["ttft_s"] is not None]
total = [r["total_s"] for r in rows]
cost = [r["cost"] for r in rows]
return {
"n": len(rows),
"ttft_p50": statistics.median(ttft),
"ttft_p95": pct(ttft, 0.95),
"total_p50": statistics.median(total),
"total_p95": pct(total, 0.95),
"cost_mean": statistics.mean(cost),
"cost_total": sum(cost),
}Common errors
- Measuring only the mean. A few slow requests can dominate user experience while the mean looks fine.
- Mixing request types. A short classification and a long summary have very different profiles. Group the summary by task or prompt version.
- Changing several things at once. If you trim the prompt and switch models together, you cannot attribute the gain.
- Ignoring retries. A request that succeeded on the third try cost three calls. Log every attempt.
- Testing at an unusual time. Latency varies with provider load, so repeat measurements at different times of day.
Exercise
Your baseline shows a mean total time of 2.1 s but a p95 of 9 s. Your cost per request is stable. Why report p95, and what would you check first?
Show answer
The mean hides a slow tail, and p95 shows what the slowest 5% of users experience. Check whether the slow requests share a cause: very long outputs (decoding time grows with output tokens), very long prompts (longer prefill), retries, or a particular task type. Grouping the logged rows by those fields usually shows which one it is.