Beyond Quotas: Choosing an LLM with Measured TTFT and TPS
High quota does not necessarily mean high usage. This article explains how to evaluate coding models using measured data instead of advertised quota: convert cost per million tokens, benchmark TTFT and TPS with a streaming script, select models by task tier, and set switching thresholds with rollback and risk controls. Readers get a practical framework for comparing models by cost, latency, throughput, and quality using their own test conditions.
1. Quota Does Not Equal Usage
A high quota does not mean high usage. When developers choose intelligent coding tools, they often treat subsidy quota as the primary criterion: the higher the quota, the more worth trying the tool seems. But after quotas have been raised many times, many users still have low actual usage. There are three main reasons:
- Inference cost determines the subsidy ceiling a platform can sustain. The more expensive a single inference is, the harder it is for the platform to offer generous quota over the long term.
- Response speed affects whether developers can keep using the tool. If waiting time is too long, developers switch back to their previous tools.
- Model capability determines whether output can pass code review. If generated code requires repeated rework, even a large quota will not be consumed continuously.
This article does not cite specific subsidy figures. Such figures often lack public sources and consistent statistical definitions, making them impossible to verify. The method below does not depend on platform announcements. It relies only on your own test data to determine whether a model is suitable for the current task.
2. Convert Cost per Million Tokens
Cost conversion is used to determine whether a solution can be sustained over time. The formula is:
Cost per million tokens = Cost per hour ÷ Tokens per hour × 1,000,000
Tokens per hour is converted from measured tokens per second:
Tokens per hour = Tokens per second (token/s) × 3600 × utilization
Utilization is the proportion of test time during which the device is actually producing output. If you calculate at full load, use 1.
Here is a demonstration calculation. The numbers do not represent any platform’s pricing. One card costs CNY 20 per hour and produces 2,000 tokens per second under the target configuration, with utilization set to 1. Output per hour is 2,000 × 3600 = 7,200,000 tokens, or 7.2 million tokens. The cost per million tokens is 20 ÷ 7,200,000 × 1,000,000 ≈ CNY 2.78.
Before calculating, you must state the assumptions clearly. Otherwise, two results cannot be compared:
- Cost basis: card type, cloud provider or self-hosted, billing method (on-demand, monthly, or spot), and whether storage and network fees are included.
- Throughput basis: input and output lengths, concurrency, warmup count, number of samples, and whether you are counting output tokens or input plus output tokens.
The parameters that affect throughput and latency are as follows:
| Parameter | Impact on throughput | Impact on TTFT | Impact on quality | Testing recommendation |
|---|---|---|---|---|
| Concurrency | Higher concurrency usually increases total throughput | TTFT increases when requests queue | Basically no impact | Test single concurrency and target concurrency separately, and record both |
| Input length | Longer input makes prefill more time-consuming | Increases significantly | Very long context may reduce accuracy | Fix at the median length of real tasks, and test one longer input setting separately |
| Output length | Determines the sample size for TPS calculation | Basically no impact | Truncation breaks completeness | Fix max_tokens and record the finish reason |
| Warmup | Data is unstable during cold start | Cold start raises TTFT | None | Discard the first 3 requests |
| Number of samples | Results fluctuate more with few samples | P95 is unstable with few samples | None | At least 30 runs per group; report P50 and P95 |
| Temperature | None | None | Affects reproducibility | Set to 0 during testing |
This conversion is valid only under the tested configuration. If input length or concurrency changes, retest and recalculate.
3. Measure TTFT and TPS with a Script
TTFT (Time To First Token) is the time from sending a request to receiving the first output token. It determines how long users wait before they see output.
TPS (Tokens Per Second) is the generation speed of output tokens. In this article, it is defined as: number of output tokens ÷ (end time − first token time). It does not include the waiting time before the first token.
The two cannot replace each other. For short-output tasks such as inline completion, TTFT is the most critical metric. For long code generation and refactoring, TPS determines total elapsed time.
The script uses an OpenAI-compatible streaming interface and requires Python 3.9 or later and the httpx library.
pip install httpx
Save the following content as bench.py:
import argparseimport jsonimport mathimport osimport timeimport httpxdef pct(values, p):"""Calculate a percentile using the nearest-rank method; return None if values is empty."""if not values:return Nones = sorted(values)idx = max(0, math.ceil(p / 100 * len(s)) - 1)return s[idx]def run_once(client, url, headers, model, prompt, max_tokens):payload = {"model": model,"messages": [{"role": "user", "content": prompt}],"max_tokens": max_tokens,"temperature": 0,"stream": True,"stream_options": {"include_usage": True},}start = time.perf_counter()first_at = Noneend_at = Nonechunk_count = 0usage_tokens = Nonetry:with client.stream("POST", url, headers=headers, json=payload) as resp:if resp.status_code != 200:return {"ok": False, "error": f"HTTP {resp.status_code}"}for line in resp.iter_lines():if not line.startswith("data:"):continuedata = line[5:].strip()if data == "[DONE]":breakobj = json.loads(data)if obj.get("usage"):usage_tokens = obj["usage"].get("completion_tokens")choices = obj.get("choices") or []if choices and (choices[0].get("delta") or {}).get("content"):if first_at is None:first_at = time.perf_counter()chunk_count += 1end_at = time.perf_counter()except (httpx.HTTPError, json.JSONDecodeError) as e:return {"ok": False, "error": type(e).__name__}if first_at is None or end_at is None:return {"ok": False, "error": "no_content"}out_tokens = usage_tokens or chunk_countdecode_time = end_at - first_atreturn {"ok": True,"ttft": first_at - start,"tps": out_tokens / decode_time if decode_time > 0 else None,"out_tokens": out_tokens,}def main():ap = argparse.ArgumentParser(description="TTFT and TPS benchmark script")ap.add_argument("--base-url", required=True, help="e.g. https://your-endpoint/v1")ap.add_argument("--model", required=True)ap.add_argument("--prompt-file", required=True)ap.add_argument("--max-tokens", type=int, default=512)ap.add_argument("--warmup", type=int, default=3)ap.add_argument("--n", type=int, default=30)ap.add_argument("--timeout", type=float, default=120.0)args = ap.parse_args()api_key = os.environ["LLM_API_KEY"]url = args.base_url.rstrip("/") + "/chat/completions"headers = {"Authorization": f"Bearer {api_key}"}with open(args.prompt_file, encoding="utf-8") as f:prompt = f.read().strip()results = []with httpx.Client(timeout=args.timeout) as client:for _ in range(args.warmup):run_once(client, url, headers, args.model, prompt, args.max_tokens)for _ in range(args.n):results.append(run_once(client, url, headers, args.model, prompt, args.max_tokens))ok = [r for r in results if r["ok"]]ttfts = [r["ttft"] for r in ok]tpss = [r["tps"] for r in ok if r["tps"]]def r3(x):return round(x, 3) if x is not None else Nonereport = {"model": args.model,"samples": len(results),"error_rate": round(1 - len(ok) / len(results), 4),"ttft_p50_s": r3(pct(ttfts, 50)),"ttft_p95_s": r3(pct(ttfts, 95)),"tps_p50": r3(pct(tpss, 50)),"tps_p5": r3(pct(tpss, 5)),}print(json.dumps(report, ensure_ascii=False, indent=2))if __name__ == "__main__":main()
Before running, put the key in an environment variable. Do not write it into code or commit it to a repository:
export LLM_API_KEY="your-api-key"python bench.py --base-url https://your-endpoint/v1 --model model-a \--prompt-file prompts/code_task.txt --max-tokens 512 --n 30
The output fields mean the following:
ttft_p50_sandttft_p95_s: median and 95th percentile of first-token latency. P95 represents the experience of slow requests and reflects risk better than an average.tps_p50: median generation speed.tps_p5: low-end generation speed. TPS problems usually appear in slow requests, so the low end is more useful than the high end.error_rate: proportion of failed requests. Failed requests are not included in TTFT and TPS, so the error rate must be reviewed separately.
Also note the following:
- Some interfaces do not return the usage field. In that case, the script approximates output tokens using the number of streaming chunks. The result will have some deviation, and the report should note this.
- Test different models alternately during similar time periods to avoid comparing under different load conditions.
- Test prompts should use desensitized or public samples. Do not put customer data or internal source code into prompts.
- Use at least 30 samples per group. With too few samples, P95 can easily be skewed by one or two outliers.
4. Tiered Model Selection and Switching Thresholds
Different tasks have different requirements for speed, quality, and cost. Model selection should be tiered by task type rather than using a single global model.
First, establish a baseline using one week of daily data. Record the primary model’s TTFT P50 and P95, TPS P50 and P5, and error rate for each task type. All later switching decisions should refer to this baseline.
The thresholds in the table below are examples. Replace them with your own baseline:
| Task type | Primary model condition | Backup model | Switching condition |
|---|---|---|---|
| Inline completion | TTFT P95 no more than 1.5 seconds | Model B | TTFT P95 exceeds 2× baseline in 3 consecutive 10-minute windows, or error rate exceeds 3% |
| Function-level generation and unit tests | Sampled pass rate no lower than 80% | Model B | Pass rate drops by 10 percentage points for one consecutive week |
| Code review and refactoring | Sampled miss rate no higher than 10% | Model C | Miss rate exceeds 10% for two consecutive weeks |
| Batch offline tasks | Unit cost below budget ceiling | Model D | Unit cost exceeds ceiling by 20%, or TPS P5 falls below half of baseline |
Switching rules require attention to the following:
- Anti-flapping: switch only after multiple consecutive windows exceed the threshold. A single fluctuation should not trigger a switch, or the team will switch back and forth frequently.
- Rollback: while the backup model is running, probe the primary model once per hour. Switch back to the primary model only after its metrics return to within 110% of baseline and remain there for 3 windows.
- Logging: write a log for every switch, including time, reason, triggered metric values, and operator.
- Tier boundaries: inline completion and code review should not share the same switching rule. The former focuses on latency, while the latter focuses on quality.
5. Risk Control and Checklist
Quota cannot be the sole basis for model selection. Cost, speed, and quality all need measured data, along with clear risk controls. Confirm each item before launch:
- Data privacy: keys, customer data, and unpublished source code are not sent to unreviewed endpoints. Test samples use desensitized or public data.
- Cost ceiling: set daily and monthly budgets, and set token limits for individual tasks. Automatically alert or degrade when limits are exceeded.
- Quality sampling: sample a fixed batch of generated results every week, record pass rate and miss rate, and compare against baseline.
- Vendor lock-in: access models through a unified invocation layer. Business code should not directly depend on vendor-specific fields or parameters.
- Degradation and rollback: the backup path can be switched with one action, and the rollback process is rehearsed once per quarter.
- Data verification: use official documentation and billing pages for price, quota, and plan information. Record the query date, statistical basis, and page update time.
- Decision basis: the selection report includes cost conversion, measured TTFT and TPS results, and quality sampling results, with test conditions stated.
Using the method in this article, you can compare models with your own data, set switching conditions, and stop losses promptly when cost or quality problems appear.
