Mastering AI agents
How to Check Claude Code Token Usage: Full Tutorial with ccusage and Python (2026)
How I built the weekly token and cost charts: the ccusage commands, the Python that turns its JSON into chart numbers, and a second script that sums the local transcripts to split out subagent usage.
Kelvin Wang · · 5 min read
Key points
- ccusage reads the local transcripts under ~/.claude/projects. No login, no API key, and it only sees this machine.
- ccusage claude weekly --json gives tokens and API-equivalent cost per week and per model; weeks with no use are left out, so fill them with 0 before charting.
- ccusage can't tell subagents apart, but their transcripts live in a subagents/ folder, so summing the files yourself splits them out.
How to Set Subagent Models in Claude Code and Codex opens with three charts: where 30 days of tokens went, tokens per week, and API-equivalent cost per week. All the numbers come from two tools run on my Mac: ccusage for the two weekly charts, and a small Python script for the subagent one. Both only read local files. Nothing needs a login, and nothing is sent anywhere.
What is ccusage and how do you install it?
ccusage is an open-source command-line tool. It reads the transcripts Claude Code keeps on disk (the .jsonl files under ~/.claude/projects/), adds up the tokens in every reply, and prices them at public API rates1. You can run it without installing:
npx ccusage@latest claude weekly
If you use it often, install it globally (I used npm):
npm install -g ccusage
ccusage claude weekly
A few things to keep in mind:
- It only sees this machine. The transcripts are local, so other computers or a cloud box running Claude Code need their own run.
- The cost is not a bill. On a subscription you pay the monthly fee; this number only says what the same tokens would cost at API prices. Inside Claude Code,
/usageshows your own usage2. - Add
claudeto the commands. From version 20, ccusage also counts Codex and other AI tools by default. Every command in this post is written asccusage claude …so it counts Claude Code only; the JSON fields are unchanged. I made the charts with 18.0.5, which counted only Claude Code. - Run it by hand, not from the status line. Each run reads every transcript; a status line runs once per refresh in every window, so with several windows open it holds several GB of memory. What to use in the status line instead, with measurements, is in the Claude Code status line memory test.
Which commands show weekly usage?
ccusage claude weekly # one row per week: tokens, cost, models used
ccusage claude weekly --breakdown # each week split by model
ccusage claude weekly --json > weekly.json # machine-readable
ccusage claude daily # per day; monthly for per month
Weeks start on Sunday in your local time zone by default. --start-of-week monday changes the first day, --timezone Asia/Taipei sets the zone, and --since 20260901 limits the range1.
How do you turn the ccusage JSON into weekly bar charts?
The --json output is a weekly array. Each week has totalTokens and totalCost, and modelBreakdowns holds each model’s tokens and cost. Before charting I did three things:
- Filled in empty weeks. A week with no transcripts doesn’t appear at all, so a chart drawn straight from the JSON skips it and looks continuous. My weeks of 8/2 and 8/9 were like that; they become 0.
- Converted tokens and split cost by model. The cost chart stacks models, so each model needs its own series.
- Projected the unfinished week. At export, the week of 11/15 was 2.49 days old, so I scaled the average pace to 7 days: 3.42 billion × 7 ÷ 2.49 ≈ 9.64 billion tokens, US$913 × 7 ÷ 2.49 ≈ US$2,571. The chart draws it as a dotted outline, separate from what was actually used.
The script’s printed labels are in Chinese, as I ran it; the logic is the same in any language.
"""把 `ccusage claude weekly --json` 轉成每週長條圖要的數字。
用法:ccusage claude weekly --json > weekly.json && python3 weekly_chart.py weekly.json
可以在最後加匯出時間(例如 2026-11-17T11:40),推估就照那個時間點算;不加就用現在。
"""
import json, sys
from datetime import date, datetime, timedelta, timezone
data = json.load(open(sys.argv[1]))["weekly"]
TZ = timezone(timedelta(hours=8)) # 跟 ccusage 一樣用本機時區分週(台北)
now = datetime.fromisoformat(sys.argv[2]).replace(tzinfo=TZ) if len(sys.argv) > 2 else datetime.now(TZ)
# 1. 沒用的週 ccusage 不會列出來,補成 0,時間軸才不會跳過
first = date.fromisoformat(data[0]["week"])
last = date.fromisoformat(data[-1]["week"])
by_week = {w["week"]: w for w in data}
weeks = []
d = first
while d <= last:
weeks.append(d.isoformat())
d += timedelta(days=7)
# 2. 每週 token(億)和每個模型的換算費用(美元)
models = sorted({m["modelName"] for w in data for m in w["modelBreakdowns"]})
tokens = [round(by_week[w]["totalTokens"] / 1e8, 2) if w in by_week else 0 for w in weeks]
cost = {m: [] for m in models}
for w in weeks:
per = {m["modelName"]: m["cost"] for m in by_week.get(w, {}).get("modelBreakdowns", [])}
for m in models:
cost[m].append(round(per.get(m, 0), 2))
# 3. 最後一週還沒過完:照目前的平均速度推到 7 天
start = datetime.fromisoformat(weeks[-1]).replace(tzinfo=TZ)
days = min(7, (now - start).total_seconds() / 86400)
cur = by_week[weeks[-1]]
print("週:", [w[5:] for w in weeks])
print("token(億):", tokens)
for m in models:
print(f"{m}(美元):", cost[m])
print(f"最後一週過了 {days:.2f} 天")
if days < 7:
print(f"推到週末:{cur['totalTokens'] / 1e8 * 7 / days:.1f} 億 token、"
f"{cur['totalCost'] * 7 / days:,.0f} 美元")
Run it like this:
ccusage claude weekly --json > weekly.json
python3 weekly_chart.py weekly.json 2026-11-17T11:40
The last argument is when I exported the JSON, so the projection uses that moment. Leave it out and it uses the current time, which gives different numbers from the chart. Token counts print in units of 100 million (億); divide by 10 for billions. The printed arrays go straight into the article’s bar chart component.
How do you measure what subagents used?
ccusage adds up everything on the machine and can’t separate the main session from subagents. Claude Code stores subagent transcripts in a separate subagents/ folder, so reading the files yourself splits them. The script:
- Counts the last 30 days only, filtering on each line’s
timestamp. - Counts each reply once. A reply is written to the transcript several times, so it dedupes on the message
id. - Adds all four token types: input, cache writes, cache reads and output. Over 90% are cache reads, because every turn rereads what came before.
"""加總 Claude Code 本機對話紀錄,看 30 天內主對話和 subagent 各用了多少 token、跑哪個模型。
用法:python3 subagent_split.py
"""
import collections, datetime, glob, json, os
ROOT = os.path.expanduser("~/.claude/projects")
cut = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=30)).isoformat()
agg = collections.defaultdict(collections.Counter)
seen = set()
for f in glob.glob(ROOT + "/**/*.jsonl", recursive=True):
kind = "subagent" if "/subagents/" in f else "主對話" # subagent 的紀錄放在 subagents/ 資料夾
for line in open(f, errors="ignore"):
if '"usage"' not in line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
if d.get("timestamp", "") < cut:
continue
m = d.get("message") or {}
u, mid = m.get("usage"), m.get("id")
if not u or not mid or (kind, mid) in seen: # 同一則回覆會寫好幾行,用 id 去重
continue
seen.add((kind, mid))
model = m.get("model", "?")
if model.startswith("<"): # 合成的訊息,不是真的 API 呼叫
continue
family = next((k for k in ("opus", "sonnet", "haiku", "fable") if k in model), model)
agg[(kind, family)]["token"] += sum(u.get(k, 0) for k in (
"input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"))
total = sum(c["token"] for c in agg.values())
for (kind, family), c in sorted(agg.items(), key=lambda kv: -kv[1]["token"]):
print(f"{kind:8} {family:7} {c['token'] / 1e8:7.1f} 億 {c['token'] / total:6.1%}")
sub = sum(c["token"] for (k, _), c in agg.items() if k == "subagent")
print(f"合計 {total / 1e8:.1f} 億,subagent 佔 {sub / total:.1%}")
python3 subagent_split.py
My Mac has about 1,470 transcript files, and one run takes about half a minute. The 30 days roll back from now, so every run gives a different answer: when I wrote that post it was about 15 billion tokens with subagents at 47%; a few hours later it was 14.6 billion and 50.3%, because the oldest day dropped out and I had just dispatched a lot of subagents.
Go deeper Which Claude Code status line uses the least memory? ccusage, ccstatusline and claude-pace with 6 windows open (2026) Why ccusage does not belong in the status line, what to use instead, and measured memory for each tool. GitHub kelvin-sl/cc-usage-lite A lightweight status line that reads only stdin, to replace ccusage statusline while you keep ccusage for reports.Sources
Kelvin Wang
Electrical engineer building tools with AI agents, sharing hands-on notes on engineering and investing.
More about me