Course contents · Lesson 12 of 16

LLM Latency and Cost: Measure and Reduce Both

Quality, Cost and Safety · Lesson 12 of 16 · 12 min Hands-on

Your handbook assistant answers well, but colleagues say each answer takes ten seconds, and your manager asks what a hosted API would charge for the whole company. Both are questions of LLM latency and cost. Here you read Ollama's timing fields, measure ten runs, cut both and estimate the bill.

Two meters: latency and tokens

Latency is the time from sending a request until the whole answer has arrived. The time to first token (TTFT) is the time until the first word appears, what a chat user notices first.

Hosted providers price input tokens, what you send, and output tokens, what the model writes, per million, with output usually dearer. Ollama counts both in every reply (lesson 2): prompt_eval_count in, eval_count out. In a RAG prompt, most tokens in are retrieved chunks.

Read the timing fields in Ollama's reply

A streamed reply ends with a chunk holding "done": true and a summary of the work. Durations are in nanoseconds, billionths of a second, so divide by 1e9 for seconds. The lab's --raw flag prints that chunk; from a cold first run, trimmed and illustrative:

{"model": "llama3.2:3b", "done": true, "done_reason": "stop",
 "total_duration": 12531442708, "load_duration": 3480213541,
 "prompt_eval_count": 912, "prompt_eval_cached_count": 0, "prompt_eval_duration": 5719847000,
 "eval_count": 49, "eval_duration": 3221906958}

Read it like a receipt: load_duration is 3.48 s loading the model into memory, prompt_eval_duration 5.72 s reading 912 tokens in, and eval_duration 3.22 s writing 49 tokens out. total_duration, 12.53 s, is the whole request as the server saw it.

Timeline of two requests on one axis from 0 to 13 seconds, illustrative. Run 1, cold: load_duration 3.48 s, then prompt_eval_duration 5.72 s for 912 tokens in, then eval_duration 3.22 s for 49 tokens out; the first token arrives at 9.29 s, right after the prompt is read; total_duration 12.53 s. Run 2, warm: load_duration 0.04 s because keep_alive kept the model loaded, prompt_eval_duration 5.50 s for 897 tokens in with 74 cached, eval_duration 3.31 s for 51 tokens out, first token at 5.62 s, total_duration 8.90 s. Footer: eval_count divided by eval_duration times 1e9 is about 15.2 tokens per second.
The first word waits for the load and the whole prompt; warm runs skip the load.

The aha: the first token comes only after the whole prompt is read, so load time and prompt length decide how long the screen stays empty. In run 2 the start of the prompt matched the previous request, so Ollama reused 74 tokens from a cache: prompt_eval_cached_count counts them, and prompt_eval_duration covers only the rest.

Tokens per second is writing speed: eval_count / eval_duration * 1e9, here 49 / 3221906958 × 1e9, about 15.2. Ollama does not report the time to first token, so ask() in the lab's timing.py streams the reply and times the first piece of text itself. Simplified:

first_token = None
start = time.perf_counter()
with requests.post(f"{OLLAMA_URL}/api/chat", json=body, stream=True, timeout=(5, 300)) as response:
    for line in response.iter_lines():
        if not line:
            continue
        chunk = json.loads(line)
        if first_token is None and chunk.get("message", {}).get("content"):
            first_token = time.perf_counter() - start
        if chunk.get("done"):
            break
latency = time.perf_counter() - start

time.perf_counter() is Python's clock for intervals, and body is the /api/chat request of lesson 2 without "stream": false. The long read timeout covers a cold start.

Why the first call is slower: keep_alive

The first request after a start or a quiet spell loads about 2 GB of weights into memory: that is load_duration. Ollama then keeps the model loaded for 5 minutes after each request by default (lesson 1), so later requests skip the load.

The request field keep_alive changes that time, as the Ollama FAQ describes: a duration such as "30m", seconds as a number, 0 to unload after the reply, or a negative number to stay loaded. OLLAMA_KEEP_ALIVE sets the server's default; the request's value wins. In 01-ollama-setup, docker compose exec ollama ollama ps lists loaded models and, under UNTIL, when each unloads.

A loaded model holds its memory, so a long keep_alive trades RAM for speed. The lab unloads the model first, with no messages and keep_alive 0, so run 1 starts cold.

Measure ten runs and read the summary

One request tells you little: timings wobble, and the first is special. measure.py in course-labs/building-llm-apps/12-latency-cost asks ten handbook questions. Its context stands in for retrieval: four 800-character handbook chunks, starting with the file that answers, so no index or embedding model is needed. With Ollama on port 11434 and llama3.2:3b pulled:

cd course-labs/building-llm-apps/12-latency-cost
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 measure.py --runs 10

pip should end with Successfully installed. Then a row appears as each run finishes, several seconds apart on a laptop CPU, and a summary. Trimmed, with illustrative numbers:

run  latency  1st token   load  prompt     gen    in  cached   out  tok/s
  1   12.61s      9.29s  3.48s   5.72s   3.22s   912       0    49   15.2
  2    8.98s      5.62s  0.04s   5.50s   3.31s   897      74    51   15.4
...

                                average       p95
latency                          9.24 s   12.61 s
time to first token              5.95 s    9.29 s
tokens per second                  15.3
tokens in per model call            900
tokens out per model call            49
Run 1 took 12.61 s, 3.48 s of it loading the model; runs 2 to 10 averaged 8.87 s.
Estimated hosted cost at $0.50 in and $1.50 out per million tokens (made-up example prices):
  these 10 requests $0.0052, per request $0.000524, per 10,000 requests $5.24

It worked if you see ten rows, the summary and a slower run 1. cannot connect to Ollama means the container is stopped; HTTP 404 means the model is not pulled, and the error prints the pull command.

p95 is the time that 95 of every 100 requests stay at or under (Latency and Percentiles). With 10 runs, the nearest-rank method picks the 10th of 10 sorted times: the slowest, here the cold run. A p95 that describes users needs many real requests.

Flowchart. 1, run 20 requests with measure.py --runs 20. 2, record every run: timings and token counts. 3, compute the average and p95 of latency, plus tokens and cost. Decision: faster or cheaper, and the eval still passes? Yes: keep it as the new baseline. No: undo it and try another change. Both lead to 4, change one thing, such as --chunks 1 or --model, and a dashed arrow back to step 1: run again, one change per run, so a moved number has one cause.
Same questions, same run count, one change at a time.

This is lesson 11's habit applied to speed: keep a change only if the eval still passes; a fast wrong answer is no improvement.

Six ways to cut latency and cost

Each lever is a measure.py flag, and most cut both meters.

  • A smaller model: once pulled, --model llama3.2:1b is faster but may answer worse, so rerun the eval.
  • Shorter prompts: the system rule and chat history are resent on every call (lesson 3).
  • Fewer or smaller chunks: --chunks 1 or --chunk-size 400 cuts tokens in and the time to first token, but may drop the fact: with one chunk, the sick leave question should get I do not know.
  • A cap on output: num_predict in options limits tokens out, with no cap by default. --num-predict 20 cuts answers mid-sentence, with done_reason length; asking for short answers is gentler.
  • Streaming: the total stays the same, but people start reading at the first token.
  • Caching repeated questions: --runs 20 --cache answers runs 11 to 20 from a dictionary, without the model. A real cache also keys on model and prompt, and is cleared when documents change.

What the same traffic would cost on a hosted API

Cost per request = tokens in × input price ÷ 1,000,000 + tokens out × output price ÷ 1,000,000. The table uses made-up prices: $0.50 in and $1.50 out per million tokens.

Table with example token counts and made-up prices of 0.50 dollars per million tokens in and 1.50 out. Four chunks, the lab default: 900 in, 50 out, 0.000450 plus 0.000075 is 0.000525 dollars per request, 5.25 dollars per 10,000 requests. One chunk: 300 in, 50 out, 0.000225 per request, 2.25 per 10,000. Four chunks with long answers: 900 in, 300 out, 0.000900 per request, 9.00 per 10,000. Notes: one chunk instead of four costs less than half; long answers cost most because output is priced three times higher; locally there is no token bill, but hardware, electricity and waiting time.
Fewer chunks more than halve the bill; long answers grow it fastest.

The default, 900 tokens in and 50 out, costs $0.000525 per request, or $5.25 per 10,000; the lab prints $5.24 from measured averages. The aha is the last row: output costs three times as much, so long answers grow the bill fastest. It is an estimate, because each model's tokenizer, the rule that splits text into tokens, counts the same text differently.

Locally there is no token bill: you pay in hardware, electricity and time. Ollama here answers one request at a time by default, so at an illustrative 9 seconds each, a laptop serves about 400 an hour.

Check yourself

Ten runs give a p95 of 12.6 s. Does one user in twenty wait that long?

No. With 10 runs the p95 is just the slowest run, the cold start, which users of a warm app rarely hit. Describing users takes many real requests.

With one chunk instead of four, tokens per second barely moves, yet answers arrive much sooner. Why?

Tokens per second measures writing, which did not change. Fewer tokens in shorten prompt_eval_duration, the reading, and the time to first token with it.

A teammate sets keep_alive to -1 so that no user ever waits for a load. What does that cost?

Memory: the model stays loaded until it is unloaded or the server restarts, so its gigabytes are never free for other programs.