How to Benchmark LLM API Cost and Response Speed: A Practical Guide

    This guide explains how to evaluate pay-per-use LLM APIs beyond their list prices. It breaks the bill into measurable variables (cache hits, input and output tokens), shows how cache hit rate and output ratio change cost conclusions, defines three core latency metrics (TTFT, output throughput, segmented throughput), and provides a step-by-step method to isolate whether slowdowns come from the network, the client, or the server. Sample Python code and a pre-launch checklist are included.

    1. List Price Does Not Equal Real Cost

    For pay-per-use LLM APIs, the bill is determined by several variables working together: how many input tokens hit the cache, how many must be recomputed, how many output tokens are generated, and how long the context of each request is. Comparing two services only by “price per million tokens” is often misleading, for two reasons.

    First, pricing for cached tokens varies widely. Under the same list price, the actual cost can differ by several times depending on the cache hit ratio.

    Second, output tokens usually cost more per token than input tokens. Even a small change in the output share can noticeably shift the total cost.

    Therefore, when selecting a service, you should plug your real business usage into each pricing plan and compare the resulting bills, not the list prices.

    2. Break the Bill Down into Computable Variables

    Total cost can be expressed as:

    1. C = In_miss × P_in + In_hit × P_cache + Out × P_out

    Here, In_miss is the number of input tokens that missed the cache, In_hit is the number of cached input tokens, Out is the number of output tokens, and P_* are the corresponding unit prices.

    Below is an example of estimation code:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Usage:
    4. input_tokens: int # Total input tokens, including the cached portion
    5. cached_tokens: int # Tokens that hit the cache
    6. output_tokens: int # Output tokens
    7. @dataclass
    8. class Pricing:
    9. input_per_m: float # Price for non-cached input, per million tokens
    10. cache_per_m: float # Price for cached input, per million tokens
    11. output_per_m: float # Price for output, per million tokens
    12. def estimate_cost(u: Usage, p: Pricing) -> float:
    13. miss = u.input_tokens - u.cached_tokens
    14. if miss < 0 or u.cached_tokens < 0 or u.output_tokens < 0:
    15. raise ValueError("Abnormal token statistics; please check the log fields")
    16. return (miss * p.input_per_m
    17. + u.cached_tokens * p.cache_per_m
    18. + u.output_tokens * p.output_per_m) / 1_000_000

    When using this code, keep the following in mind:

    • Statistics should come from the usage fields returned by the service or from request logs, not from rule-of-thumb estimates.
    • If the service uses time-of-day pricing, calculate peak and off-peak costs separately, then weight them by the actual call times.
    • Dividing the result by the total token count yields an “effective unit price,” which is better suited for cross-service comparison than the list price.

    3. How Cache Hit Rate and Output Ratio Change the Conclusion

    Multi-turn conversations, agent tasks, and coding-assistant scenarios repeatedly send the same prefix, including system instructions, tool definitions, and conversation history. These scenarios can achieve a very high cache hit rate, and the price of the cached portion largely determines the bill.

    Cache hits depend on an exactly identical prefix. Therefore, the order of content in a request directly affects cost. A simple rule of thumb in practice: put stable content first and dynamic content last.

    The output ratio reflects the task type. For retrieval, code reading, and long-document summarization, input far exceeds output, so the output price has limited impact. When generating long text or large blocks of code, the output share rises and the cost structure changes accordingly.

    If the provider does not return cache-hit statistics, you can log a hash of each request’s prefix locally and estimate the hit rate from the proportion of repeated prefixes. Estimated results should be labeled with an error margin and not treated as exact data.

    4. Three Core Metrics for Response Speed

    To judge whether a model service is “slow,” you need to look at three separate metrics.

    Metric Meaning What It Tells You
    Time to First Token (TTFT) Time from sending the request to receiving the first output chunk Reflects queuing, network, and prefill overhead
    Output throughput (tokens/s) Average speed during the generation phase Reflects the service’s actual generation capability
    Segmented throughput Separate speeds for reasoning content and the final answer Prevents merged statistics from hiding problems

    Some models output a reasoning process first and then the final answer. The speeds of these two segments can differ noticeably. If you only look at the combined average, it is hard to tell which segment is causing the problem.

    The following code shows how to measure throughput by segment:

    1. import time
    2. def measure_stream(chunks):
    3. """
    4. chunks: an iterable where each element is (kind, text),
    5. with kind being either 'reasoning' or 'answer'.
    6. Character count is only an approximation; formal statistics
    7. should use the token usage returned by the service.
    8. """
    9. t0 = time.perf_counter()
    10. first_latency = None
    11. counts = {"reasoning": 0, "answer": 0}
    12. spans = {}
    13. for kind, text in chunks:
    14. now = time.perf_counter()
    15. if first_latency is None:
    16. first_latency = now - t0
    17. counts[kind] += len(text)
    18. if kind not in spans:
    19. spans[kind] = [now, now]
    20. spans[kind][1] = now
    21. report = {"ttft_s": first_latency}
    22. for kind, (start, end) in spans.items():
    23. duration = end - start
    24. report[f"{kind}_chars_per_s"] = counts[kind] / duration if duration > 0 else None
    25. return report

    5. Isolate the Latency Source: Network, Client, or Server

    When speed degrades, the problem may lie in one of three places: the local network, the client implementation, or server capacity. Troubleshoot in the following order.

    1. Rule out local issues. At the same time, from the same network environment, test another service known to be stable. If both slow down simultaneously, the problem is most likely your local network or proxy.
    2. Run synchronized comparison tests. Send structurally identical requests to multiple services at the same time. Only if the target service alone slows down can you attribute the problem to that service.
    3. Check status codes. A 429 usually indicates rate limiting, 5xx indicates a server-side error, and timeouts should be recorded separately. Rate-limit rules should be based on the official API documentation, not guesswork.
    4. Plot time-of-day curves. If speed drops in sync with peak hours, the service is likely under-provisioned. If only one specific model or channel slows down, that model’s queuing or concurrency quota may be the cause.

    Keep raw logs at every step, including request timestamps, first-byte time, last-byte time, and status codes. Without raw data, later conclusions are hard to reproduce.

    6. Let Users Know What the System Is Doing

    When there is no output for a long time, users cannot tell “the service is stuck” from “the service is slow.” If the UI only shows a loading spinner, users will assume the system has failed.

    A better approach is to display explicit status information:

    • Queued: the request has been sent but has not yet been assigned processing resources;
    • Reasoning: show the growth of reasoning content, or the current reasoning speed;
    • Generating: show the output speed and the length produced so far;
    • Error: provide the error code and a suggested action, such as retrying or switching to a fallback.

    For developer tools, you can also offer an optional view of the reasoning process. This lets users identify which stage is slow, reducing unnecessary interruptions and misdiagnosis.

    7. Pre-Launch Checklist for Selection and Rollout

    1. Sample real traffic. Samples should cover the full business cycle, including peaks and troughs; do not rely on synthetic data alone.
    2. Bucket by task type. Code generation, retrieval Q&A, and long-text summarization differ greatly in cache hit rate and output ratio, so cost and latency should be calculated separately for each.
    3. Set service-level targets. For example, require the 95th percentile of TTFT to stay below a threshold. The threshold should be driven by business needs, not copied from someone else’s numbers.
    4. Design degradation and failover mechanisms. When latency or error rates exceed thresholds, automatically switch to a fallback and record the number and reason of each switch.
    5. Build routine monitoring. This should include daily cost reports, latency percentile curves, error-code distribution, and cache-hit trends.

    8. Conclusion

    Evaluating an LLM API requires attention to both cost structure and response experience. On the cost side, break the bill into variables such as cache, input, and output, and compute an effective unit price using real usage. On the speed side, separate TTFT, segmented throughput, and time-of-day curves, and use controlled comparisons to distinguish network, client, and server problems. Only when both kinds of data are recorded can service selection and troubleshooting rest on a reliable foundation.