How to Benchmark LLM API Cost and Latency: A Practical Evaluation Method
Learn how to evaluate LLM API services beyond headline pricing: build a token-based cost model accounting for cache hits and output ratios, factor in time-of-day pricing differences, measure time-to-first-token and generation speed separately, and run a structured selection process to pick the right model service for your workload.
1. Why Sticker Price Alone Isn’t Enough
When teams compare model providers, the first thing they look at is usually the per-million-token price on the pricing page. That number is useful, but it’s only one factor in the final bill. What you actually pay is determined by three things: the total token volume of your requests, the price differences across token types, and how the provider meters usage.
Take a pay-as-you-go inference service as an example. A typical request includes input tokens and output tokens. Some input tokens may hit a cache, and cached tokens are usually billed at a significantly lower rate than uncached ones. Output tokens generally cost more than input tokens. As a result, two workloads on the same price sheet can end up with bills that differ by several times, simply because their input/output structure and cache hit patterns are different.
So before comparing unit prices, answer three questions first: How large is your total token volume? What fraction of your input can hit the cache? What fraction of your tokens are output? Only with those answers does a unit-price comparison mean anything.
2. Building the Cost Model
Here is a general cost estimation formula. Let total billable tokens be T, the output ratio be r_out, and the cache hit rate be r_hit:
- Output tokens: T × r_out
- Input tokens: T × (1 − r_out)
- Cached input tokens: input tokens × r_hit
- Uncached input tokens: input tokens × (1 − r_hit)
Total cost is the sum of each token category multiplied by its respective unit price. The code below performs the estimation. All prices are placeholder parameters and should be replaced with the actual prices published by the provider.
def estimate_cost(total_tokens: int,output_ratio: float,hit_ratio: float,price_hit: float,price_miss: float,price_output: float) -> float:"""total_tokens: total billable token countoutput_ratio: fraction of output tokens, between 0 and 1hit_ratio: cache hit ratio within input tokens, between 0 and 1price unit: currency per million tokensreturns: estimated cost"""output_tokens = total_tokens * output_ratioinput_tokens = total_tokens - output_tokenshit_tokens = input_tokens * hit_ratiomiss_tokens = input_tokens - hit_tokenscost = (hit_tokens * price_hit+ miss_tokens * price_miss+ output_tokens * price_output) / 1_000_000return cost# Example: assume 1 billion tokens, 1% output ratio, 90% cache hit rate# Prices are placeholders, only to demonstrate the calculation flowprint(estimate_cost(1_000_000_000, 0.01, 0.90, 0.2, 2.0, 8.0))
There are two assumptions in this model that are easy to overlook.
First, the way cache hits are measured can vary by platform. Some platforms report cached token counts directly in the bill; others only report total volume. If the platform doesn’t expose hit data, your estimate will carry significant error, so you should record the duplication level of input tokens separately during testing.
Second, the output ratio affects cost more than intuition suggests. Because output tokens are usually priced higher, even if output accounts for only one percent of total volume, its share of the total bill can far exceed one percent. For workloads dominated by long-context reading, input caching matters more; for generation-heavy tasks, the output price is the decisive factor.
3. Bringing the Time Dimension into Cost
The same service can have different prices and speeds at different times of day. Some providers charge more during peak hours or throttle concurrency when demand is high. Cost evaluation should therefore be broken down by time period rather than reduced to a single average.
A practical approach:
- Log the token volume, cache hit status, and duration of every request at hourly or half-hourly granularity.
- Group the data by time period and compare per-unit costs between off-peak and peak hours.
- Compute a weighted average to get the true business cost, using actual usage per period as weights.
If your workload is concentrated in specific windows—for example, batch jobs running during the morning peak—an all-day average will underestimate cost. Conversely, if tasks can be scheduled into off-peak hours, that alone saves money. This kind of scheduling strategy often delivers more immediate gains than switching models.
4. Measure Latency and Throughput Separately
LLM response latency typically has two phases. The first is time to first token (TTFT): the time from sending the request to receiving the first output chunk. The second is the generation phase: the rate at which the model emits subsequent tokens. For models with an explicit reasoning phase, you should also distinguish reasoning content from the final answer, since the two may stream at different speeds.
Looking only at total duration hides problems. Slow TTFT with fast generation, and fast TTFT with slow generation, can produce similar total times while delivering completely different user experiences.
The code below shows how to record TTFT and generation rate separately. Because tokenizers split text differently, character count is used here as an approximation of token count; for a formal evaluation, use the provider’s token counts or a consistent tokenizer.
import timedef measure_stream(stream):"""stream: an iterable generator of text chunksreturns first-chunk latency, generation rate (approx. tokens/s), and total duration"""start = time.monotonic()first_latency = Noneunits = 0for chunk in stream:now = time.monotonic()if first_latency is None:first_latency = now - startunits += len(chunk)end = time.monotonic()total = end - startif first_latency is None:return {"ttft": None, "rate": 0.0, "total": total}generation_time = end - (start + first_latency)rate = units / generation_time if generation_time > 0 else 0.0return {"ttft": first_latency, "rate": rate, "total": total}
Points to keep in mind when sampling:
- Take multiple samples within the same time window and report medians and percentiles, not a single run.
- Record request timestamps so results can be correlated with billing data and service status.
- Track the reasoning phase and answer phase separately, computing rates for each.
5. Observability and User Perception
The value of streaming output goes beyond showing text sooner. It also tells users the system is working. If the interface shows nothing but a spinner with no progress information, users can’t tell whether the model is reasoning slowly or the connection has dropped.
Consider the following when designing the interaction:
- Show the current stage, such as “queued,” “reasoning,” or “generating answer.”
- Display the real-time generation rate so users can judge whether waiting is worthwhile.
- When reasoning content is visible, let users expand it, but don’t require all reasoning to be displayed.
- If no output arrives beyond a threshold, show a clear timeout message with a retry option.
This information matters just as much to developers. Logs should record TTFT, generation rate, retry counts, and error types for every request. With that data, you can determine whether a problem lies in the network, server-side queuing, or your own implementation.
6. Selection and Rollout Recommendations
When evaluating a model service, build a comparison table covering these dimensions:
| Dimension | How to measure | What to watch |
|---|---|---|
| Unit cost | Estimate using your real token structure | Cache hits, output ratio |
| Peak vs. off-peak gap | Break down billing by time period | Peak surcharges and queuing |
| Time to first token | Sample repeatedly, use percentiles | Interactive experience |
| Generation rate | Measure per phase | Long-text generation time |
| Stability | Log errors and retries | Availability |
A suggested rollout sequence:
- Run real production request samples for a week, recording token structure and latency.
- Use the cost model to estimate monthly spend for each candidate, with separate peak and off-peak scenarios.
- Run latency sampling against candidate services, focusing on percentiles rather than averages.
- Validate with a small traffic slice first, and only cut over fully once error rates and user feedback are acceptable.
The final choice should reflect your workload’s cost sensitivity and experience requirements. For offline batch jobs, cost and throughput matter most; for interactive scenarios, TTFT and streaming feedback matter most.
7. Common Pitfalls
- Looking only at unit price while ignoring output ratio and cache hits.
- Treating a single test run as representative of long-term behavior, ignoring time-of-day variation.
- Measuring only total duration, making it impossible to locate which phase is slow.
- Providing no progress feedback in the UI, leading users to assume the service has failed.
Avoiding these pitfalls is more valuable than chasing any single metric. Cost, speed, and transparency need to be considered together to support stable long-term use.
