How to Evaluate Large Language Models: Quality, Speed, and Cost

    Choosing a large language model (LLM) is hard when open-source and closed models update constantly and community debates stay at the level of vague claims like "model A is stronger than model B" or "model B is much faster." Such arguments usually rest on different task types, parameters, prompts, and access channels, so the conclusions rarely transfer to your own use case. This guide breaks LLM evaluation into three core dimensions—quality, speed, and cost—and a five-step workflow. It covers building scenario-based test sets, running a reproducible evaluation pipeline behind a unified scoring interface, combining objective and subjective scoring, and turning results into engineering decisions such as tiered routing, cost and capacity planning, and continuous regression testing. It also lists common pitfalls so you can move "which model is better" from a subjective argument to a quantifiable, reproducible engineering conclusion.

    Three Core Dimensions for Evaluating a Model

    Quality: are outputs correct, stable, and on target?

    Quality gets the most attention and is also the most easily oversimplified. “Can the model solve math problems” or “does the generated code run” are only subsets of quality. A more complete assessment breaks quality into three layers:

    • Correctness: is the answer factually correct, does the code pass test cases, and does every step of a math derivation hold;
    • Compliance and formatting: does it follow format constraints, such as producing valid JSON, filling in the specified fields, or using a required citation format;
    • Consistency: does it reach the same conclusion across multiple generations of the same question, and is the variance in output style controllable.

    In practice, quality is often equated with benchmark scores. But the sources of questions, scoring scripts, and prompt templates in public benchmarks are often opaque; a high score only shows that a model does well on a certain class of problems and cannot directly predict its performance on your private business data.

    Speed: latency and throughput

    Speed is not a single number; it includes at least three metrics:

    • Time to first token (TTFT): the time from sending a request to receiving the first token, which determines the “first-screen experience” in streaming interactions;
    • Inter-token latency (ITL): the average interval between tokens during generation, which determines the smoothness of the output;
    • Throughput (tokens/s): the total number of tokens the system produces per unit time, which determines the overall time and unit cost of batch tasks.

    The “fast” that users perceive usually comes from a combination of low TTFT and stable ITL. For batch inference, offline data processing, and similar scenarios, you should focus more on total throughput under a given concurrency.

    Cost: from unit price to per-task cost

    Unit price is the most intuitive metric, but what really determines your budget is per-task cost:

    Per-task cost = (input tokens × input unit price + output tokens × output unit price) × average number of calls

    The reason to multiply by the number of calls is that real systems are rarely “one call, one deliverable”:

    • For open-ended generation, the common “generate several candidates and pick the best” strategy multiplies the call count;
    • Agent applications must loop repeatedly through “think—call a tool—observe the result”;
    • When a timeout occurs or the output format is non-compliant, retries are needed.

    If the task is long and complex, the reasoning process the model outputs is itself counted as output tokens. So evaluating cost must be tied to the real call chain, not just the sticker price.

    Beyond these three dimensions, you should also watch context length and effective utilization under long contexts, the stability of function calling and structured output, and service capabilities such as streaming output and concurrency quotas.

    Task Stratification: Different Scenarios Demand Different Capabilities

    Mapping the evaluation dimensions onto concrete scenarios gives you a “scenario–capability” table:

    Scenario type Typical tasks Core need Recommended focus
    Creative divergence Brainstorming, naming, first-draft copywriting Diversity and inspiration in the output Focus on creative quality; generate in parallel with several models and then blend
    High-frequency interaction Intelligent customer service, code completion, instant Q&A Stable output under low latency and high concurrency TTFT and throughput, with quality treated as a “good enough” baseline
    Execution tasks Code generation and refactoring, document structured extraction Correctness and verifiability Whether it passes tests and can be parsed directly by downstream programs
    Deep reasoning Math proofs, complex solution analysis, long technical documents Completeness and rigor of the reasoning chain Step-by-step derivation; higher latency and cost are acceptable
    High-compliance Financial, medical, and government Q&A Controllable, traceable output with no data leakage Access isolation, audit logs, and private or dedicated deployment

    Two scenarios are especially worth expanding on.

    For execution tasks, the key is not “intelligence” but the balance between “speed” and “verifiability.” Code completion and simple refactoring have a clear upper bound on single-output quality requirements: code either passes tests or it does not. When the pass rates among a few candidate models differ only slightly, generation latency and throughput become the deciding factors. Every order-of-magnitude reduction in latency noticeably reduces the developer’s sense of waiting and clearly increases effective output per unit time per task.

    Deep-reasoning tasks are the opposite. For tasks like math proofs and cross-module architecture design, a single wrong step often makes the entire conclusion unusable. Users are usually willing to pay several times the time and token cost for a higher single-shot success rate. In these tasks, the weight of “can it get it right” is far higher than “how fast it is.”

    From “Model Strength” to “System Trade-offs”

    Treating model strength as the only axis makes it easy to overlook three systemic factors.

    Multiple generations can compensate for a single-shot gap

    Suppose model A has a single-shot success rate of 0.70 on a task and model B has 0.80, and the task has an automatically verifiable success criterion—for example, code passes unit tests, or an answer can be compared against a reference result. Using a “generate k results in parallel and pick one” strategy, the task success rate is computed as:

    Task success rate = 1 − (1 − single-shot success rate)^k

    • Model A generating 3 results reaches roughly 1 − 0.30³ ≈ 0.973;
    • Model B generating only 1 stays at 0.80.

    Ignoring the extra latency from parallelism, the call ratio between the two is 3 : 1. Here model A’s overall performance is actually better. This shows that a model which is “slightly weaker in quality but faster” can make up the gap on verifiable tasks by increasing the number of samples, and whether it is worthwhile depends on the ratio of single-call cost to task value. Of course, this conclusion rests on the premise that “success can be automatically determined.” For open-ended writing tasks where quality is hard to judge automatically, the quality gaps between models still need to be taken seriously.

    Speed changes the design space for interaction

    Low latency is not just an experience issue; it also changes the product’s form. When TTFT and output speed are high enough, you can design shorter interaction rounds, more immediate human-AI collaboration, and finer-grained streaming feedback. When a single generation takes tens of seconds, product design is forced to introduce asynchronous tasks, progress indicators, and result notifications, and the interaction path grows longer.

    Deployment form determines cost structure and bargaining power

    A model’s capabilities show up not only in official APIs but also in whether it can be deployed efficiently in-house.

    • For inference throughput, GPU memory capacity and bandwidth, batch scheduling strategy, KV-cache management, quantization precision, and parallel sharding all significantly affect the actual throughput of a single card or a single rack. Real-world measurements from some organizations show that, after thorough optimization, the per-rack throughput of the same model can be far higher than an untuned baseline.
    • For supply structure, open-weight models that can be self-deployed let users choose a hybrid “self-hosted + API” supply based on their own traffic curves, reducing dependence on a single provider. This is one of the most fundamental commercial differences between open models and purely closed APIs.

    Therefore, the “strongest” model is not necessarily the solution with the highest overall return; you need to weigh per-task cost, supply stability, and data-compliance requirements together.

    Building a Reproducible Evaluation Pipeline

    The core reason subjective experience struggles to reach consensus is the lack of a reproducible evaluation process. A minimal viable evaluation pipeline has four parts.

    Build a scenario-based test set

    The test set should come from real business, not a public question bank:

    1. Sample real requests from production logs, and after de-identification, organize them into fixed cases;
    2. Label each case with an expected result or an automated judging rule;
    3. The case set is usually no fewer than 100–200 items, covering common phrasings, boundary inputs, and long-tail questions;
    4. Put the case set under version control. After updating a model or prompt, regress against the same cases to judge the actual gains from a change.

    Unify the calling and scoring interfaces

    Wrap model calls behind a unified interface that hides the protocol differences between providers, so evaluation scripts stay decoupled from specific models:

    1. import statistics as st
    2. import time
    3. from dataclasses import dataclass
    4. from typing import Any, Callable
    5. @dataclass
    6. class ModelConfig:
    7. name: str # Model identifier
    8. endpoint: str # Endpoint URL
    9. temperature: float = 0.0
    10. @dataclass
    11. class EvalCase:
    12. messages: list[dict]
    13. checker: Callable[[str], float] # Returns a score between 0 and 1
    14. def percentile(values: list[float], p: float) -> float:
    15. ordered = sorted(values)
    16. index = max(0, min(len(ordered) - 1, round(p / 100 * len(ordered) + 0.5) - 1))
    17. return ordered[index]
    18. def evaluate(config: ModelConfig, cases: list[EvalCase],
    19. client: Any, repeat: int = 3) -> dict:
    20. scores, latencies, tokens = [], [], []
    21. for case in cases:
    22. for _ in range(repeat):
    23. start = time.perf_counter()
    24. response = client.chat(model=config.name,
    25. messages=case.messages,
    26. temperature=config.temperature)
    27. latencies.append(time.perf_counter() - start)
    28. tokens.append(response.usage.total_tokens)
    29. scores.append(case.checker(response.text))
    30. return {
    31. "model": config.name,
    32. "score_mean": round(st.mean(scores), 4),
    33. "score_std": round(st.stdev(scores), 4) if repeat > 1 else 0.0,
    34. "latency_p50_ms": round(percentile(latencies, 50) * 1000, 1),
    35. "latency_p95_ms": round(percentile(latencies, 95) * 1000, 1),
    36. "avg_tokens": round(st.mean(tokens), 1),
    37. }
    38. # Example: evaluate multiple candidate models sequentially on the same cases
    39. # for easy side-by-side comparison
    40. configs = [
    41. ModelConfig(name="candidate_a", endpoint="..."),
    42. ModelConfig(name="candidate_b", endpoint="..."),
    43. ]
    44. results = [evaluate(cfg, cases, client) for cfg in configs]

    Engineering details during evaluation matter just as much:

    • Control variables: keep temperature, sampling parameters, max output length, and system prompts consistent, to avoid mistaking parameter differences for model differences;
    • Repeat multiple times: repeat at least 3 times, and report the mean and standard deviation so a one-off result does not mislead the decision;
    • Isolate interference: run serially, or control concurrency, to avoid models competing for resources with one another;
    • Look only at high percentiles: focus on p50 and p95 latency rather than the mean; long-tail latency is the main source of user complaints.

    Combine objective scoring with subjective review

    • Automatically judgeable: use unit-test pass rate for code tasks, field-validation pass rate for structured output, and comparison of results against reference answers for math problems.
    • Hard to judge automatically: for creative writing and solution analysis, use pairwise blind evaluation—anonymize and shuffle the outputs of two models, and have reviewers pick the better one. When conditions allow, supplement this with “model-as-a-judge,” where a stronger model scores against preset criteria. But be wary of scoring-bias preferences: the judging model may favor longer answers, particular formats, or text generated by models from the same family, so the final conclusion should still be calibrated with human spot checks.
    • Business metrics as a backstop: if conditions allow, observe real business metrics in a small-traffic canary—for example, human-takeover rate, user retry rate, and task completion rate. This is the evidence closest to real value.

    Produce a structured comparison report

    Evaluation results should be presented in a table containing at least the quality score, quality variance, p50/p95 latency, and average token consumption. When possible, convert token consumption into per-task cost using unit prices. Based on this, combined with the business’s tolerance for latency and quality, you can judge “which model is more suitable” rather than the vague “who is stronger.”

    From Evaluation Conclusions to Engineering Deployment

    Tiered routing: let each model do its job

    The most valuable use of evaluation results is not to pick a “single champion” but to build a routing layer. A simplified example:

    1. def route(task: dict) -> str:
    2. # Route by task complexity, latency tolerance, and data sensitivity level
    3. if task["sensitive"]:
    4. return "private_deployed_model" # Dedicated deployment; data never leaves your environment
    5. if task["type"] == "code_completion":
    6. return "low_latency_model" # High-frequency interaction; prioritize low latency
    7. if task["type"] in ("math_proof", "architecture_design"):
    8. return "deep_reasoning_model" # Deep reasoning; higher cost is acceptable
    9. if task["latency_budget_ms"] < 800:
    10. return "low_latency_model"
    11. return "general_model"

    The routing layer can also enable progressive escalation: first use a lightweight model to produce a draft, and when automated validation fails, hand it to a more capable model to redo. This both controls average cost and preserves the quality ceiling.

    Cost and capacity planning

    • Per-task cost accounting: multiply the average token consumption from evaluation by the unit price, add the average number of retries, and you get the real cost; then allocate budget by scenario.
    • Elastic scaling: when traffic has peaks and valleys, use container-platform autoscaling, message-queue peak-shaving, and elastic load balancing so that inference-service resources change with the load. For long-running tasks, use asynchronous task queues to avoid many timeouts caused by request pile-up.
    • Caching and reuse: for repeated prefixes such as system prompts and knowledge-base snippets, use the prefix-caching capability of inference frameworks to reduce redundant computation. Retrieval results in retrieval-augmented generation (RAG) can also be cached at the result level in object storage.
    • Self-hosted + API hybrid: stable, high-frequency baseline load can be handled by a self-hosted inference service, while elastic peaks and low-frequency complex tasks call the API. The decision is based on the break-even point, not simply on “whose unit price is lower”:

    Self-hosted monthly cost = hardware amortization + power and datacenter + operations staff
    API monthly cost = monthly request volume × average tokens per request × unit price

    You have a cost advantage only when the self-hosted monthly cost is lower than the API monthly cost.

    Observability and continuous regression

    Replacing a model is never a one-time job but a continuous process. Recommendations:

    • Log the model version, token usage, latency, and an output summary for each request, and connect them to a logging service for unified search;
    • Configure monitoring and alerting for latency percentiles, error rate, and cost;
    • Regularly regress with a fixed test set to prevent hidden degradations such as “quality drops after optimizing the prompt.”

    If you use infrastructure from cloud platforms such as Baidu AI Cloud, you can leverage their general-purpose capabilities—containers, message queues, object storage, and monitoring/alerting—to quickly build the pipeline above. Business teams then only need to focus on the evaluation criteria and routing logic themselves.

    Common Evaluation Pitfalls

    1. Substituting leaderboards for business validation: public leaderboards have opaque problems and scoring rules, and often differ markedly from real business distributions;
    2. Substituting a single experience for a system evaluation: a single generation result is random; you must use multiple repetitions and standard deviation to characterize stability;
    3. Looking only at average latency: users perceive the long-tail requests, so p95 and p99 latency are more informative than the mean;
    4. Ignoring the token-billing structure: long inputs, long chains of thought, and retries all amplify cost, so comparing only unit prices easily leads to misjudgment;
    5. Equating model capability with system capability: prompt quality, retrieval quality, and tool-call reliability also determine the final result;
    6. Frequently switching base models: each switch requires re-tuning prompts and parameters, and the hidden migration cost is often underestimated.

    Conclusion

    Evaluating a large language model is essentially finding the balance point across the three dimensions of quality, speed, and cost that matches your business constraints. Creative-divergence scenarios value diversity, high-frequency interaction scenarios value low latency, execution scenarios value correctness and verifiability, deep-reasoning scenarios value the rigor of the reasoning chain, and high-compliance scenarios care about whether data can stay within your own environment. By building scenario-based test sets, unifying evaluation interfaces, and combining objective scoring with business metrics, you can turn “which model is better” from a subjective argument into a quantifiable, reproducible engineering conclusion. On that basis, adding tiered routing, elastic scaling, and continuous regression makes model selection no longer a one-time gamble but a continuously optimizable system capability.