Testing, Evaluation, and Debugging

Measuring Latency, Cost, and Quality in the Same Experiment

Measuring Latency, Cost, and Quality in the Same Experiment
Learn how to measure latency, cost, and quality together in the same experiment to evaluate AI models and prompts effectively. This practical guide covers creating a combined run record, implementing a lightweight experiment runner, tracking token usage, estimating USD costs, and generating a side-by-side summary table to make data-driven trade-off decisions.

The first time I optimized a prompt for quality alone, latency doubled and the token bill tripled. The first time I optimized for cost alone, the structured-output failure rate climbed high enough that the retry logic erased most of the savings. Both experiments felt successful until I looked at the other two numbers. That is when I started treating latency, cost, and quality as a single measurement problem instead of three separate ones.

This post builds the smallest useful version of that combined experiment. We will run the same evaluation set through one or more configurations, record wall-clock time, input and output tokens, estimated cost, and a quality score for every example, then look at the three metrics side by side. No external experiment platform—just a clear harness you can run before you change a prompt or a model in production.

As always:

Build the smallest useful version, then test what breaks.

What You Will Have Working by the End

  • A single run record that captures latency, tokens, cost, and quality for one example

  • A small experiment runner that executes an evaluation set under one or more configurations

  • A summary table that shows average latency, total cost, and pass rate together

  • A clear view of trade-offs when you change model, prompt, or max_tokens

  • Three realistic failure modes and how to notice them early

The goal is a decision you can defend with numbers instead of anecdotes.

The Three Metrics We Will Capture

Latency – wall-clock time from the start of the Anthropic call to the moment we have a parsed result (including any retries you choose to include).

Cost – estimated USD based on input tokens, output tokens, and the published price of the model you are using. Prices change; keep them in a single constant so they are easy to update.

Quality – for this post we reuse the binary pass/fail scorer from the evaluation-dataset article. Graded scores are useful later; a clear pass rate is enough to start.

All three numbers must come from the same run of the same examples. Comparing quality from one day with cost from another day is how misleading conclusions appear.

Price Table and Cost Helper

A documentary close-up of a screen showing Python cost estimation code for AI token usage pricing.

Python

# Update these numbers from the official Anthropic pricing page.
# Values are USD per million tokens.
MODEL_PRICES = {
    "claude-sonnet-5": {"input": 3.00, "output": 15.00},   # example figures – verify current prices
    "claude-haiku-5":  {"input": 0.80, "output": 4.00},
}

def estimate_cost(model: str, input_tokens: int, output_tokens: int) -> float:
    prices = MODEL_PRICES.get(model)
    if not prices:
        return 0.0
    return (input_tokens * prices["input"] + output_tokens * prices["output"]) / 1_000_000

Never hard-code prices deep inside the runner. When the price list changes you want one place to edit.

A Combined Run Record

Python

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any

@dataclass
class RunRecord:
    example_id: str
    config_name: str
    model: str
    latency_ms: float
    input_tokens: int
    output_tokens: int
    cost_usd: float
    passed: bool
    quality_reason: str
    raw_output: Any = None
    error: str | None = None
    ran_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())

One record equals one example under one configuration. Everything we need for the summary table lives on this object.

The Experiment Runner

We assume you already have:

  • an evaluation set (EVAL_SET) of the shape defined in the earlier evaluation post

  • a scoring function (score_summary) that returns (passed: bool, reason: str)

  • a workflow function that calls Anthropic and returns a dictionary (or raises)

The runner’s only new job is to time the call, read token usage, and attach cost.

Python

import time
from anthropic import Anthropic
from dotenv import load_dotenv
import os

load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

def run_single(
    example,
    config_name: str,
    model: str,
    system: str,
    max_tokens: int = 512
) -> RunRecord:
    start = time.perf_counter()
    error = None
    output = None
    input_tokens = 0
    output_tokens = 0

    try:
        response = client.messages.create(
            model=model,
            max_tokens=max_tokens,
            system=system,
            messages=[{"role": "user", "content": example.input_text}]
        )
        input_tokens = response.usage.input_tokens
        output_tokens = response.usage.output_tokens
        raw_text = response.content[0].text.strip()
        output = json.loads(raw_text)  # may raise
    except Exception as e:
        error = f"{type(e).__name__}: {e}"

    latency_ms = (time.perf_counter() - start) * 1000
    cost = estimate_cost(model, input_tokens, output_tokens)
    passed, reason = score_summary(output, example.expected, error)

    return RunRecord(
        example_id=example.id,
        config_name=config_name,
        model=model,
        latency_ms=latency_ms,
        input_tokens=input_tokens,
        output_tokens=output_tokens,
        cost_usd=cost,
        passed=passed,
        quality_reason=reason,
        raw_output=output,
        error=error
    )

Notice that latency includes only the Anthropic call and the immediate parse. If your production path contains retries, decide explicitly whether the experiment should include those retries or measure a single attempt. Mixing the two makes comparisons meaningless.

Running an Experiment Across Configurations

Python

def run_experiment(eval_set, configurations: list[dict]) -> list[RunRecord]:
    """
    configurations = [
        {"name": "sonnet-default", "model": "claude-sonnet-5", "system": SYSTEM_A, "max_tokens": 512},
        {"name": "haiku-cheap",    "model": "claude-haiku-5",  "system": SYSTEM_A, "max_tokens": 512},
        {"name": "sonnet-strict",  "model": "claude-sonnet-5", "system": SYSTEM_B, "max_tokens": 256},
    ]
    """
    records = []
    for config in configurations:
        print(f"\n=== Config: {config['name']} ===")
        for example in eval_set:
            print(f"  {example.id}...", end=" ", flush=True)
            record = run_single(
                example,
                config_name=config["name"],
                model=config["model"],
                system=config["system"],
                max_tokens=config.get("max_tokens", 512)
            )
            status = "PASS" if record.passed else "FAIL"
            print(f"{status}  {record.latency_ms:.0f}ms  ${record.cost_usd:.5f}")
            records.append(record)
    return records

Three configurations is enough to see trade-offs. More than five usually produces noise instead of insight.

The Summary Table

A documentary photo of a developer reviewing terminal logs for AI experiment comparison of cost, latency, and quality.

Python

from collections import defaultdict

def summarize(records: list[RunRecord]) -> None:
    by_config = defaultdict(list)
    for r in records:
        by_config[r.config_name].append(r)

    print("\n=== Experiment Summary ===")
    print(f"{'config':<20} {'pass%':>7} {'avg_ms':>8} {'p95_ms':>8} {'total$':>9} {'avg$':>9}")
    print("-" * 70)

    for name, group in sorted(by_config.items()):
        n = len(group)
        pass_rate = 100 * sum(1 for r in group if r.passed) / n
        latencies = sorted(r.latency_ms for r in group)
        avg_ms = sum(latencies) / n
        p95_ms = latencies[int(0.95 * (n - 1))] if n > 1 else latencies[0]
        total_cost = sum(r.cost_usd for r in group)
        avg_cost = total_cost / n
        print(f"{name:<20} {pass_rate:>6.1f}% {avg_ms:>7.0f} {p95_ms:>7.0f} {total_cost:>8.4f} {avg_cost:>8.5f}")

The table answers the only question that matters when you are choosing a configuration:

  • How often is the output good enough?

  • How long does a typical call take, and how bad is the tail?

  • What will this cost at the volume I actually expect?

Everything else is secondary.

Interpreting the Trade-offs

A few patterns appear repeatedly:

  • A stricter system prompt often improves pass rate and sometimes reduces output tokens (lower cost) while adding a small amount of latency.

  • A cheaper / faster model usually reduces latency and cost and sometimes reduces pass rate. The summary table shows you the exact size of that drop.

  • Lowering max_tokens can cut both cost and latency; it can also increase structural failures if the model runs out of room mid-JSON.

The right choice depends on the product constraint that is currently binding. If users abandon a flow after two seconds, latency dominates. If the monthly bill is the problem, cost dominates. If downstream systems keep breaking on bad JSON, quality dominates. Measure all three so you can see the real trade-off instead of guessing.

Three Failure Modes Worth Catching Early

1. Comparing Different Example Sets

If configuration A is evaluated on ten easy cases and configuration B on ten hard cases, the summary table is meaningless. Always run every configuration on the identical evaluation set.

2. Forgetting Retries in One Configuration

If one config includes a retry and another does not, latency and cost are no longer comparable. Decide once whether the experiment measures a single attempt or the full production path, and apply that decision uniformly.

3. Stale Prices

Cost numbers that use last quarter’s prices will push you toward the wrong model. Keep the price table in one place and update it when Anthropic publishes new numbers.

Practical Rules for Combined Experiments

  • Record tokens from the API response; do not estimate them from character counts.

  • Use wall-clock time around the real call, not a separate “model latency” field the API may or may not provide.

  • Run the same evaluation set for every configuration in the experiment.

  • Prefer a small number of well-understood configurations over a large grid search you will never look at.

  • Store the raw records. When a later question appears (“what was the p95 for the strict prompt?”) you can re-aggregate without re-running the model.

What This Experiment Does Not Cover Yet

It does not:

  • Produce statistical significance tests

  • Automatically choose the best configuration

  • Track quality with graded (0–1) scores

  • Measure cache-hit rates or prompt-caching savings

  • Run continuously in CI

Those capabilities belong to later testing and production posts. The goal today is a single experiment that makes the three-way trade-off visible.

Verification Checklist

  1. Run two configurations on the same five-example set and confirm the summary table shows pass rate, latency, and cost for both.

  2. Intentionally switch to a cheaper model and confirm cost falls and the pass rate is still reported.

  3. Lower max_tokens dramatically and confirm you can see the effect on both failure rate and cost.

  4. Inspect a single RunRecord and confirm it contains latency, tokens, cost, and the quality reason.

  5. Re-run the identical experiment and confirm the numbers are stable enough to support a decision (small variance is normal; large swings usually mean the evaluation set is too small or too noisy).

If all five steps pass, you have a working combined experiment.

Update Note

Model identifiers and published prices change. Always verify the current model IDs and the current per-token prices in the official Anthropic documentation and pricing page before you rely on the cost column for a real decision. The measurement pattern itself—same examples, same three metrics, side-by-side summary—remains useful regardless of those surface changes.

Looking Ahead

The next post walks through a complete trace-based debugging session for a failed agent. Once you can measure quality, latency, and cost together, the remaining hard problems are usually interaction failures inside multi-step loops. A clear trace is the fastest way to see those failures.

Keep the experiment runner. When you later debate a model upgrade or a prompt rewrite, you will already have a way to put latency, cost, and quality on the same page.

Build the smallest useful version, then test what breaks.

— Caleb Fletcher

Boise, Idaho

Updated · 2026-10-22 15:18
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Context & Tools. All rights reserved. data-driven, published weekly ♥