Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

docs(benchmarks): reproducible cost/memory/latency scripts behind "How it compares"

Rach Pradhan9d6a00544f73
diff --git a/README.md b/README.md
index 7db1bc00..996069c9 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ Run the same job on graff, Claude Code, and Codex (three read-only questions abo
**Scripts and CI finish in half the time.** For one-shot runs (`graff -p`, the SDKs, a CI step), graff completed a gpt-5.5 turn in **4.4 s** versus Codex's **8.9 s** on the identical ChatGPT endpoint, on every single trial. That is graff's near-instant startup beating a heavier per-call launch. In a long interactive session the startup amortizes and both settle to model latency, so this is a one-shot and automation win, not a blanket "graff is faster."
-<sub><b>Method:</b> macOS, same machine, read-only code questions on this repo. Cost is each tool's own reported usage at <a href="https://codegraff.com/docs/models">codegraff gateway prices</a>; memory is peak RSS via <code>/usr/bin/time -l</code>; latency is 8 concurrent graff/Codex pairs on a tool-free prompt with reasoning effort matched. Your numbers will vary with the task, the model, and the network.</sub>
+<sub><b>Method:</b> macOS, same machine, read-only code questions on this repo. Cost is each tool's own reported usage at <a href="https://codegraff.com/docs/models">codegraff gateway prices</a>; memory is peak RSS via <code>/usr/bin/time -l</code>; latency is 8 concurrent graff/Codex pairs on a tool-free prompt with reasoning effort matched. Your numbers will vary with the task, the model, and the network. Reproduce it yourself: <a href="benchmarks/">benchmarks/</a>.</sub>
---
## Under the hood
diff --git a/benchmarks/README.md b/benchmarks/README.md
new file mode 100644
index 00000000..f69ab65d
--- /dev/null
+++ b/benchmarks/README.md
@@ -0,0 +1,47 @@
+# Benchmarks
+
+Reproducible head-to-head of **graff** vs **Claude Code** vs **Codex**, behind the
+numbers in the main README's [How it compares](../README.md#how-it-compares).
+
+These are small, honest benchmarks (a few read-only code questions on one
+machine), not a leaderboard. Run them yourself. Your numbers will vary with the
+task, the model, and the network.
+
+## Prerequisites
+
+- `graff`, `claude`, and `codex` on your PATH, each authenticated.
+- For `latency.py`, graff must be logged into Codex (`graff login codex`) so that
+ `graff --model codex` hits the same ChatGPT endpoint as `codex exec` (no gateway).
+- macOS for `memory.py` (it uses BSD `/usr/bin/time -l`).
+- Python 3.
+
+## What each script measures
+
+| Script | Measures | Result we got |
+| --- | --- | --- |
+| `cost.py` | USD per task (each tool's own usage, [gateway prices](https://codegraff.com/docs/models)) | graff/deepseek-v4-pro **$0.022** vs Claude Code/Opus-4.8 **$0.51** vs Codex/gpt-5.5 **$0.42** |
+| `memory.py` | Peak RSS + CPU (`/usr/bin/time -l`) | graff **~25 MB** floor vs Node **~410 MB** vs Rust **~206 MB** |
+| `latency.py` | One-shot turn latency, same gpt-5.5 endpoint, concurrent pairs | graff **4.4 s** vs codex **8.9 s** (one-shot only) |
+
+```sh
+python3 benchmarks/cost.py
+python3 benchmarks/memory.py
+python3 benchmarks/latency.py 8
+```
+
+Tasks live in `tasks.py` (edit to test other work).
+
+## Honest caveats (please read)
+
+- **Cost is model freedom, not token savings.** On the *same* model, graff and
+ Codex use comparable tokens (graff is leaner on single-tool lookups, heavier on
+ multi-tool tasks because it makes more tool-calling rounds, each re-sending
+ cached context). graff is cheaper because it can run a cheap capable model where
+ Claude Code is Claude-only and Codex is GPT-only.
+- **Speed is a one-shot win.** `latency.py` measures cold-start `-p` / `exec`
+ invocations, where graff's tiny Zig startup beats Codex's heavier per-call
+ launch. In a long interactive session this amortizes and turns are model-bound.
+- **Memory is task-dependent.** graff's RSS grows with how much code it reads into
+ context, so the floor (~25 MB) is the headline, not a fixed number.
+- `cost.py` omits graff on `gpt-5.5`: the codegraff gateway alias is not in graff's
+ local price table, so graff reports `$0` for it (deepseek/glm price fine).
diff --git a/benchmarks/cost.py b/benchmarks/cost.py
new file mode 100755
index 00000000..34b9f8a0
--- /dev/null
+++ b/benchmarks/cost.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python3
+"""Cost per task: graff vs Claude Code vs Codex on the shared tasks.
+
+Each tool reports cost differently, so we normalize to USD:
+ * Claude Code : total_cost_usd from `claude -p --output-format json`
+ * Codex : computed from its reported tokens at gpt-5.5 gateway prices
+ * graff : turn.cost_usd from `graff --model <m> --json` (gateway-metered)
+
+We benchmark graff on cheap models that the gateway prices (deepseek-v4-pro,
+glm-5.2). graff cannot self-meter the gateway `gpt-5.5` alias (not in its local
+price table, so it returns $0), which is why it is omitted here. The cost story
+is model freedom, not the harness: on the SAME model token usage is comparable.
+
+Prereqs: graff, claude, codex on PATH and authenticated.
+Run: python3 benchmarks/cost.py
+"""
+import subprocess, json, time, os, statistics
+from tasks import TASKS
+os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+# codegraff gateway prices, USD per 1M tokens: (input, output, cached_input)
+# https://codegraff.com/docs/models
+PRICES = {"gpt-5.5": (5.00, 30.00, 0.50)}
+GRAFF_MODELS = ["deepseek-v4-pro", "glm-5.2"]
+
+def sh(cmd, stdin="", timeout=360):
+ t = time.time()
+ try:
+ p = subprocess.run(cmd, input=stdin, capture_output=True, text=True, timeout=timeout)
+ return p.stdout, round(time.time() - t)
+ except subprocess.TimeoutExpired:
+ return "", round(time.time() - t)
+
+def claude(task):
+ out, w = sh(["claude", "-p", TASKS[task], "--output-format", "json"])
+ try: d = json.loads(out)
+ except Exception: d = {}
+ m = (list((d.get("modelUsage") or {}).keys()) or ["?"])[0]
+ return ("Claude Code", m, d.get("total_cost_usd"), w)
+
+def codex(task):
+ # codex exec reads stdin; empty stdin (the default here) gives EOF so it uses
+ # the positional prompt instead of hanging.
+ out, w = sh(["codex", "exec", "-s", "read-only", "--json", TASKS[task]])
+ usage = None
+ for l in out.splitlines():
+ try: e = json.loads(l)
+ except Exception: continue
+ if e.get("type") == "turn.completed": usage = e.get("usage")
+ u = usage or {}
+ inp, cached = u.get("input_tokens", 0), u.get("cached_input_tokens", 0)
+ outp = u.get("output_tokens", 0) + u.get("reasoning_output_tokens", 0)
+ pi, po, pc = PRICES["gpt-5.5"]
+ cost = ((inp - cached) * pi + cached * pc + outp * po) / 1e6 if inp else None
+ return ("Codex", "gpt-5.5", cost, w)
+
+def graff(task, model):
+ req = json.dumps({"type": "user", "text": TASKS[task]}) + "\n"
+ out, w = sh(["graff", "--model", model, "--json"], stdin=req)
+ cost = None
+ for l in out.splitlines():
+ try: e = json.loads(l)
+ except Exception: continue
+ if e.get("type") == "turn": cost = e.get("cost_usd")
+ return ("graff", model, cost, w)
+
+rows = []
+for task in TASKS:
+ print(f"=== {task} ===", flush=True)
+ for fn in (claude, codex):
+ tool, m, cost, w = fn(task); rows.append((tool, m, cost))
+ print(f" {tool:12s} {m:18s} ${(cost if cost is not None else float('nan')):.4f} {w}s", flush=True)
+ for gm in GRAFF_MODELS:
+ tool, m, cost, w = graff(task, gm); rows.append((tool, m, cost))
+ print(f" {tool:12s} {m:18s} ${(cost if cost is not None else float('nan')):.4f} {w}s", flush=True)
+
+print("\n=== average USD/task ===")
+for tool, m in [("Claude Code", None), ("Codex", "gpt-5.5"), ("graff", "deepseek-v4-pro"), ("graff", "glm-5.2")]:
+ cs = [c for (t, mm, c) in rows if t == tool and (m is None or mm == m) and c is not None]
+ if cs: print(f" {tool} / {m or '?'}: ${statistics.mean(cs):.4f}")
diff --git a/benchmarks/latency.py b/benchmarks/latency.py
new file mode 100755
index 00000000..498b85a2
--- /dev/null
+++ b/benchmarks/latency.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""One-shot turn latency, SAME model + endpoint: graff `--model codex` vs `codex exec`.
+
+Both hit ChatGPT gpt-5.5 directly via ~/.codex/auth.json (NO codegraff gateway),
+with reasoning effort matched to `high`, on a tool-free prompt (pure round-trip).
+Each trial launches both CONCURRENTLY so they share the same network conditions,
+then we print the distribution so you can tell a real gap from noise.
+
+Caveat: this is one-shot / scripted mode (cold start each run). In a long
+interactive session the startup cost amortizes and it becomes model-bound, so this
+is an automation / `-p` / SDK speed result, not a blanket \"graff is faster\".
+
+Prereqs: graff + codex on PATH; logged into Codex (`graff login codex`).
+Run: python3 benchmarks/latency.py [N] (default N=8 trials)
+"""
+import subprocess, json, time, threading, statistics, sys
+
+PROMPT = ("What is 17 times 23? Reply with only the number, nothing else. "
+ "Do not use any tools or read any files.")
+N = int(sys.argv[1]) if len(sys.argv) > 1 else 8
+
+def graff(res):
+ req = '{"type":"set_effort","level":"high"}\n' + json.dumps({"type": "user", "text": PROMPT}) + "\n"
+ t = time.time()
+ subprocess.run(["graff", "--model", "codex", "--json"], input=req,
+ capture_output=True, text=True, timeout=180)
+ res["g"] = time.time() - t
+
+def codex(res):
+ t = time.time()
+ subprocess.run(["codex", "exec", "-s", "read-only", "--json",
+ "-c", "model_reasoning_effort=high", PROMPT], input="",
+ capture_output=True, text=True, timeout=180)
+ res["c"] = time.time() - t
+
+gt, ct = [], []
+for i in range(N):
+ res = {}
+ tg = threading.Thread(target=graff, args=(res,))
+ tx = threading.Thread(target=codex, args=(res,))
+ tg.start(); tx.start(); tg.join(); tx.join()
+ gt.append(res["g"]); ct.append(res["c"])
+ print(f"trial {i+1}: graff={res['g']:5.1f}s codex={res['c']:5.1f}s", flush=True)
+
+gm, cm = statistics.mean(gt), statistics.mean(ct)
+print(f"\ngraff --model codex: mean={gm:.2f}s sd={statistics.pstdev(gt):.2f} range={min(gt):.1f}-{max(gt):.1f}")
+print(f"codex exec: mean={cm:.2f}s sd={statistics.pstdev(ct):.2f} range={min(ct):.1f}-{max(ct):.1f}")
+d = cm - gm
+print(("graff faster by %.1fs (%.0f%%)" % (d, 100 * d / cm)) if d > 0
+ else ("codex faster by %.1fs (%.0f%%)" % (-d, 100 * -d / gm)))
diff --git a/benchmarks/memory.py b/benchmarks/memory.py
new file mode 100755
index 00000000..4a8bf1e4
--- /dev/null
+++ b/benchmarks/memory.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Peak memory (RSS) + CPU per tool, via BSD `/usr/bin/time -l` (macOS).
+
+Measures the MAIN process of each tool: graff (tiny Zig binary), Claude Code
+(Node), Codex (Rust). Each also spawns helpers (shell commands, code-intel) that
+are NOT counted here. graff's RSS scales with how much code it reads into
+context, so expect a range across tasks.
+
+Prereqs: graff, claude, codex on PATH and authenticated; macOS.
+Run: python3 benchmarks/memory.py
+"""
+import subprocess, json, os, re
+from tasks import TASKS
+os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+def time_l(cmd, stdin=""):
+ p = subprocess.run(["/usr/bin/time", "-l"] + cmd, input=stdin,
+ capture_output=True, text=True, timeout=360)
+ rss = user = sys_ = None
+ for l in p.stderr.splitlines():
+ if "maximum resident set size" in l:
+ try: rss = int(l.strip().split()[0])
+ except Exception: pass
+ m = re.search(r"([\d.]+)\s+real\s+([\d.]+)\s+user\s+([\d.]+)\s+sys", l)
+ if m: _, user, sys_ = map(float, m.groups())
+ return (rss or 0) / 1048576, (user or 0) + (sys_ or 0)
+
+for task in TASKS:
+ print(f"=== {task} ===")
+ g_rss, g_cpu = time_l(["graff", "--model", "deepseek-v4-pro", "--json"],
+ json.dumps({"type": "user", "text": TASKS[task]}) + "\n")
+ c_rss, c_cpu = time_l(["claude", "-p", TASKS[task], "--output-format", "json"])
+ x_rss, x_cpu = time_l(["codex", "exec", "-s", "read-only", "--json", TASKS[task]])
+ print(f" graff (Zig) RSS={g_rss:7.1f} MB CPU={g_cpu:.1f}s")
+ print(f" Claude Code (Node) RSS={c_rss:7.1f} MB CPU={c_cpu:.1f}s")
+ print(f" Codex (Rust) RSS={x_rss:7.1f} MB CPU={x_cpu:.1f}s")
diff --git a/benchmarks/tasks.py b/benchmarks/tasks.py
new file mode 100644
index 00000000..e2639d69
--- /dev/null
+++ b/benchmarks/tasks.py
@@ -0,0 +1,24 @@
+"""Shared benchmark tasks: read-only questions about this repo (src/main.zig).
+
+Read-only on purpose, so no agent can look good by editing files. Each tool runs
+the SAME prompt. Edit these freely to test other kinds of work.
+"""
+
+TASKS = {
+ "runEval": (
+ "In src/main.zig of this repository, what does the function runEval do, "
+ "and which other functions or methods does it call? Answer in 4-5 "
+ "sentences. Do not modify any files."
+ ),
+ "permgate": (
+ "In this repository, how does the permission gate decide whether a bash "
+ "command needs approval, and what rule lets read-only commands run "
+ "without prompting? Name the key function(s) by name. Answer in 4-5 "
+ "sentences. Do not modify any files."
+ ),
+ "providers": (
+ "In this repository, list the AI model providers graff supports, and for "
+ "each give its wire-format/auth style and the environment variable for "
+ "its API key. Be concise. Do not modify any files."
+ ),
+}