Perf take 4 (§58): 0.49.0 vs 0.43.0 on opentitan — §46's didOpen fix 14× in the release build, the eager codeAction path 2×, the tail rename at 11×, the index +14%; harness committed in tools/perf/; findings filed for loop 3
This commit is contained in:
1 parent
414d501847
commit
d10e57aa6e
19 files changed
+2999
-9
No files matched your search
@@ -0,0 +1,104 @@
|
||||
# `tools/perf` — the lucisv performance harness
|
||||
|
||||
Take 1's, take 2's and take 3's measurement clients all lived in a scratch
|
||||
directory and all three are gone; take 3's numbers had to be re-derived from
|
||||
take 2's *prose*. This directory is the fix. Everything a performance round
|
||||
needs is here, in Python 3 with **no third-party packages**, so it runs from a
|
||||
clean checkout given an opentitan path and a pair of binaries.
|
||||
|
||||
Written for take 4 (`docs/performance_take4.md`, TODO §58). Take 5 reuses it.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `lspclient.py` | framed JSON-RPC over a `lucisv-server` child process: the `workspace/configuration` pull answered per session, per-session client capabilities (with and without `codeAction.resolveSupport`), `storagePath` cache control, `window/logMessage` capture including a `--verbose` server's own `timing:` lines |
|
||||
| `sites.py` | every opentitan position a phase measures, named by the *text* it wants rather than a line number |
|
||||
| `harness.py` | what every phase shares: the registry, the run's configuration, the session factory, the recorder |
|
||||
| `bench.py` | the command line, and the phases that reproduce take 3's tables |
|
||||
| `phases_new.py` | the phases for what 0.44–0.49 added: the new offer sites, §49's surface, §46's `didOpen` fix, `moduleHierarchy`, index size and RSS |
|
||||
| `sweep.sh` | the timed CLI sweeps (`format --check`, `check`) over five trees, `/usr/bin/time -l` |
|
||||
| `sweeptable.py` | those logs → the document's §7 Markdown table |
|
||||
| `outcomes.sh` | the untimed per-file outcome runs, for the release-to-release outcome diff |
|
||||
|
||||
## The rules every run obeys
|
||||
|
||||
- **Everything goes through the guard.** `tools/guard.sh -m 8 -t 1800 --
|
||||
<command>` wraps every server session, every `lucisv` invocation and every
|
||||
`cargo` build. `sweep.sh` and `outcomes.sh` wrap their own children; wrap
|
||||
`bench.py` yourself. A guard kill is a finding — report the command and the
|
||||
limit, never raise it.
|
||||
- **The corpus is read-only.** The formatter cache goes to a scratch
|
||||
`--cache-dir`, the index cache to a scratch `storagePath`
|
||||
(`bench.py --storage`), and every edit a request returns (`rename`,
|
||||
`codeAction/resolve`) is discarded by the client. Check
|
||||
`git -C <opentitan> status --porcelain` after every phase.
|
||||
- **No `cargo` command runs anywhere while a timed phase is running**, and the
|
||||
machine's load average is noted before and after each phase.
|
||||
- **Three tries per row**, first try and repeat range both reported.
|
||||
|
||||
## Running a phase
|
||||
|
||||
```sh
|
||||
SP=/tmp/perf # scratch: caches, logs, results.jsonl
|
||||
OT=$HOME/repo/opentitan
|
||||
tools/guard.sh -m 8 -t 1800 -- python3 tools/perf/bench.py nav \
|
||||
--server target/release/lucisv-server \
|
||||
--label 0.49.0 --opentitan "$OT" \
|
||||
--storage "$SP/caches/0.49.0" --out "$SP/results.jsonl" --tries 3
|
||||
```
|
||||
|
||||
Every phase takes the same arguments. `--label` is what tells two binaries
|
||||
apart in `results.jsonl`; run each phase once per binary.
|
||||
|
||||
| Phase | Document section | What it does |
|
||||
|---|---|---|
|
||||
| `baseline` | §0 | `initialize`, and the transport floor (`$/lucisvNoSuchMethod`, rejected without work) |
|
||||
| `verbose` | §0 | four `codeAction` shapes, each with and without `--verbose`, so the server's own `timing:` line sits beside the wire |
|
||||
| `scan` | §4 | the (scope × cache state) startup matrix: `default`, `{"index":{}}`, `scopeDepth 0`, `workspace`, cold and warm |
|
||||
| `scopes` | §4b | what each scope *answers* at the `aes` instantiation — counts, not just times |
|
||||
| `nav` | §2 | the cheap per-cursor requests at workspace scope, one dedicated session each |
|
||||
| `flush` | §2 | the `didChange` flush, measured with a `foldingRange` barrier |
|
||||
| `codeaction` | §6a | the five fan-out cursors (1 / 6 / 42 / 67 / 128 files), lazy and eager |
|
||||
| `portaction` | §6 | the one opentitan cursor that offers a port refactoring: offer and `codeAction/resolve` |
|
||||
| `refactor` | §6b | the offer sites 0.44–0.49 added — expand `.*`, organize imports, inline module, port actions, and an ANSI header as the contrast — plus the extract-module *selection* |
|
||||
| `rename` | §6c | `prepareRename` and `rename` on `aes` |
|
||||
| `tailrename` | §6c | §49's hierarchical tail: a variable renamed at its declaration, named through an instance from another file |
|
||||
| `blockers` | §3 | the queue-blocking analysis: a slow leader, then the three requests an editor fires on every cursor move |
|
||||
| `widen` | §5 | the `didOpen` widen at `scopeDepth 0` and at the default scope, cold and warm |
|
||||
| `didopen` | §5/§46 | `didOpen` → the request behind it, workspace scope, the four files the perf README's 2026-09-05 table used |
|
||||
| `diagnostics` | §2 | the publish after a `didChange` (≈150 ms of it is the debounce) |
|
||||
| `completion` | §6d | the typed-prefix curve |
|
||||
| `tailcompletion` | §6d | completion after an instance head and a `.` |
|
||||
| `hierarchy` | §6 | `lucisv/moduleHierarchy`, the snapshot the DUT sidebar consumes |
|
||||
| `rss` | §6 | server RSS after the workspace scan, and the index store's size on disk |
|
||||
| `probe` | — | ad-hoc: `--probe FILE:LINE:CHAR` (0-based) prints what a cursor offers. This is how `sites.REFACTOR_SITES` was found |
|
||||
|
||||
## The CLI sweeps
|
||||
|
||||
```sh
|
||||
tools/perf/sweep.sh ~/.cache/lucisv-baselines/lucisv-0.49.0 0.49.0 "$OT" "$SP/sweep" 3
|
||||
python3 tools/perf/sweeptable.py "$SP/sweep" --labels 0.49.0,0.43.0,0.39.0
|
||||
```
|
||||
|
||||
`sweep.sh` writes one log per (label, tree, command, cache state) holding the
|
||||
three tries' `/usr/bin/time -l` blocks; `sweeptable.py` reads them all and
|
||||
prints the table plus the summary line each run reported, so a timing that
|
||||
moved because the *work* moved is not mistaken for a timing change.
|
||||
|
||||
## The outcome diff
|
||||
|
||||
```sh
|
||||
tools/perf/outcomes.sh ~/.cache/lucisv-baselines/lucisv-0.43.0 0.43.0 "$OT" "$SP/outcomes"
|
||||
tools/perf/outcomes.sh ~/.cache/lucisv-baselines/lucisv-0.49.0 0.49.0 "$OT" "$SP/outcomes"
|
||||
diff "$SP/outcomes/0.43.0.format.txt" "$SP/outcomes/0.49.0.format.txt"
|
||||
```
|
||||
|
||||
Untimed, `--no-cache`, paths rewritten relative to the corpus root and sorted,
|
||||
so two runs differ only where a per-file *outcome* did. Every difference is
|
||||
either explained by a TODO section or is a finding.
|
||||
|
||||
## `results.jsonl`
|
||||
|
||||
One JSON object per row: `phase`, `label`, `row`, `ms` (the try list, first
|
||||
try first), and whatever else the phase knows — `n` (a result count, a file
|
||||
count, a byte count), `titles`, `note`. Nothing in the document may quote a
|
||||
number that is not in this file or in a `sweep.sh` / `outcomes.sh` log.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,436 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The lucisv LSP performance phases — take 3's request table.
|
||||
|
||||
python3 tools/perf/bench.py <phase> --server <path> --label <name> \
|
||||
--opentitan DIR --storage DIR --out results.jsonl [--tries N]
|
||||
|
||||
Every phase opens its own `lucisv-server` sessions, times requests on the wire
|
||||
with `time.perf_counter`, and appends one JSON object per row to
|
||||
`results.jsonl`. Nothing is ever written into the corpus: the index cache is
|
||||
directed at `--storage`, and every edit a request returns (`rename`,
|
||||
`codeAction/resolve`) is discarded.
|
||||
|
||||
This file holds the phases that reproduce `docs/performance_take3.md`'s
|
||||
tables; `phases_new.py` holds the phases for what 0.44–0.49 added, and
|
||||
`harness.py` holds what both share. Run every invocation under
|
||||
`tools/guard.sh -m 8 -t 1800 --`; see `tools/perf/README.md`.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import harness # noqa: E402
|
||||
import sites # noqa: E402
|
||||
from harness import ( # noqa: E402
|
||||
ARGS, at, code_action_params, doc, phase, pos, record, result_count,
|
||||
session, settled, tries,
|
||||
)
|
||||
|
||||
import phases_new # noqa: E402,F401 — registers its own phases
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §0 — the transport baseline and the `--verbose` cross-check
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("baseline")
|
||||
def phase_baseline():
|
||||
with session("workspace") as s:
|
||||
init = s.initialize()
|
||||
record(phase="baseline", row="initialize", ms=[init])
|
||||
s.did_open(sites.path(sites.TB))
|
||||
s.wait_quiet(1.5)
|
||||
s.take_notifications()
|
||||
ms = tries(s, "$/lucisvNoSuchMethod", {}, 4)
|
||||
record(phase="baseline", row="transport baseline ($/lucisvNoSuchMethod)", ms=ms)
|
||||
|
||||
|
||||
@phase("verbose")
|
||||
def phase_verbose():
|
||||
"""The wire beside the server's own `timing:` line, three shapes (§0)."""
|
||||
shapes = [
|
||||
("prim_flop_2sync (128), eager", False, sites.AON_TIMER, "prim_flop_2sync #(", 2),
|
||||
("prim_flop_2sync (128), lazy", True, sites.AON_TIMER, "prim_flop_2sync #(", 2),
|
||||
("aes (6), eager", False, sites.TB, " aes #(", 2),
|
||||
("comment line", True, sites.TB, "// ", 2),
|
||||
]
|
||||
for label, lazy, relative, needle, offset in shapes:
|
||||
for verbose in (False, True):
|
||||
with session("workspace", resolve_support=lazy, verbose=verbose) as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.6)
|
||||
s.take_notifications()
|
||||
s.take_timings()
|
||||
params = at(relative, needle, 1, offset)
|
||||
params["range"] = {"start": params.pop("position"), "end": None}
|
||||
params["range"]["end"] = params["range"]["start"]
|
||||
params["context"] = {"diagnostics": []}
|
||||
ms = tries(s, "textDocument/codeAction", params, 4)
|
||||
server_ms = [t[1] for t in s.take_timings("textDocument/codeAction")]
|
||||
record(phase="verbose", row=label, ms=ms,
|
||||
note="verbose" if verbose else "quiet",
|
||||
server_ms=server_ms)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §4 — startup and scan, per scope config and cache state
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("scan")
|
||||
def phase_scan():
|
||||
"""§4 — one cell per (scope, cache state), `--tries` runs each.
|
||||
|
||||
"Cold" wipes the `storagePath` directory immediately before each run;
|
||||
"warm" leaves the previous run's store in place. The barrier is 1.5 s of
|
||||
silence after the `didOpen`, not the `$/progress` `end`, because the end
|
||||
report is followed by more indexing chatter.
|
||||
"""
|
||||
for scope in ("default", "empty-index", "depth0", "workspace"):
|
||||
for cache in ("cold", "warm"):
|
||||
runs, note = [], ""
|
||||
for _ in range(ARGS.tries):
|
||||
cold = cache == "cold"
|
||||
with session(scope, cold=cold, storage_name="scan-" + scope) as s:
|
||||
s.initialize()
|
||||
started = time.perf_counter()
|
||||
s.did_open(sites.path(sites.TB))
|
||||
s.wait_quiet(1.5)
|
||||
runs.append((time.perf_counter() - started) * 1000.0 - 1500.0)
|
||||
ends = [
|
||||
n["params"]["value"].get("message", "")
|
||||
for n in s.notifications
|
||||
if n["method"] == "$/progress"
|
||||
and n["params"]["value"].get("kind") == "end"
|
||||
]
|
||||
note = " | ".join(ends[-2:])
|
||||
record(phase="scan", row="%s, %s cache" % (scope, cache), ms=runs, note=note)
|
||||
|
||||
|
||||
@phase("scopes")
|
||||
def phase_scopes():
|
||||
"""§4b — what each scope answers at the `aes` instantiation in `tb.sv`."""
|
||||
asks = [
|
||||
("definition", "textDocument/definition", {}),
|
||||
("typeDefinition", "textDocument/typeDefinition", {}),
|
||||
("hover", "textDocument/hover", {}),
|
||||
("references", "textDocument/references", {"context": {"includeDeclaration": True}}),
|
||||
("documentHighlight", "textDocument/documentHighlight", {}),
|
||||
("signatureHelp", "textDocument/signatureHelp", {}),
|
||||
]
|
||||
for scope in ("default", "depth0", "workspace"):
|
||||
with session(scope, storage_name="scopes-" + scope) as s:
|
||||
settled(s)
|
||||
for name, method, extra in asks:
|
||||
params = dict(at(sites.TB, " aes #(", 1, 2))
|
||||
params.update(extra)
|
||||
ms = tries(s, method, params)
|
||||
_, message = s.request(method, params)
|
||||
record(phase="scopes", row="%s @ %s" % (name, scope), ms=ms,
|
||||
n=result_count(message))
|
||||
ms = tries(s, "workspace/symbol", {"query": "aes"})
|
||||
_, message = s.request("workspace/symbol", {"query": "aes"})
|
||||
record(phase="scopes", row="workspace/symbol 'aes' @ %s" % scope, ms=ms,
|
||||
n=result_count(message))
|
||||
hint = {"textDocument": doc(sites.TB),
|
||||
"range": {"start": {"line": 0, "character": 0},
|
||||
"end": {"line": 9999, "character": 0}}}
|
||||
ms = tries(s, "textDocument/inlayHint", hint)
|
||||
_, message = s.request("textDocument/inlayHint", hint)
|
||||
record(phase="scopes", row="inlayHint @ %s" % scope, ms=ms,
|
||||
n=result_count(message))
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §2 — the navigation table at workspace scope
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("nav")
|
||||
def phase_nav():
|
||||
rows = [
|
||||
("definition on aes", "textDocument/definition", at(sites.TB, " aes #(", 1, 2)),
|
||||
("hover on aes", "textDocument/hover", at(sites.TB, " aes #(", 1, 2)),
|
||||
("typeDefinition on aes", "textDocument/typeDefinition", at(sites.TB, " aes #(", 1, 2)),
|
||||
("documentHighlight", "textDocument/documentHighlight", at(sites.TB, " aes #(", 1, 2)),
|
||||
("references on aes", "textDocument/references",
|
||||
dict(at(sites.TB, " aes #(", 1, 2), context={"includeDeclaration": True})),
|
||||
("references on .clk_i", "textDocument/references",
|
||||
dict(at(sites.TB, " .clk_i", 1, 5), context={"includeDeclaration": True})),
|
||||
("signatureHelp in the port list", "textDocument/signatureHelp",
|
||||
at(sites.TB, " .clk_i", 1, 22)),
|
||||
("documentSymbol", "textDocument/documentSymbol", {"textDocument": doc(sites.TB)}),
|
||||
("foldingRange", "textDocument/foldingRange", {"textDocument": doc(sites.TB)}),
|
||||
("codeLens", "textDocument/codeLens", {"textDocument": doc(sites.TB)}),
|
||||
("documentLink", "textDocument/documentLink", {"textDocument": doc(sites.TB)}),
|
||||
("selectionRange", "textDocument/selectionRange",
|
||||
{"textDocument": doc(sites.TB), "positions": [pos(sites.TB, " aes #(", 1, 2)]}),
|
||||
("semanticTokens/full", "textDocument/semanticTokens/full",
|
||||
{"textDocument": doc(sites.TB)}),
|
||||
("inlayHint (whole file)", "textDocument/inlayHint",
|
||||
{"textDocument": doc(sites.TB),
|
||||
"range": {"start": {"line": 0, "character": 0},
|
||||
"end": {"line": 9999, "character": 0}}}),
|
||||
("diagnostic (pull)", "textDocument/diagnostic", {"textDocument": doc(sites.TB)}),
|
||||
("workspace/symbol 'aes'", "workspace/symbol", {"query": "aes"}),
|
||||
]
|
||||
for row, method, params in rows:
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
ms = tries(s, method, params, ARGS.tries + 1)
|
||||
_, message = s.request(method, params)
|
||||
record(phase="nav", row=row, ms=ms, n=result_count(message), method=method)
|
||||
|
||||
|
||||
@phase("flush")
|
||||
def phase_flush():
|
||||
"""The `didChange` flush, measured with a `foldingRange` barrier."""
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read()
|
||||
runs = []
|
||||
for version in range(2, 2 + ARGS.tries + 1):
|
||||
s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version)
|
||||
runs.append(s.ms("textDocument/foldingRange", {"textDocument": doc(sites.TB)}))
|
||||
record(phase="flush", row="didChange flush (foldingRange barrier)", ms=runs)
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §6 — codeAction, offer and resolve
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("codeaction")
|
||||
def phase_codeaction():
|
||||
for lazy in (True, False):
|
||||
for label, relative, needle, occurrence, fanout, offset in sites.FANOUT_CURSORS:
|
||||
with session("workspace", resolve_support=lazy) as s:
|
||||
settled(s)
|
||||
if relative != sites.TB:
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.6)
|
||||
s.take_notifications()
|
||||
params = code_action_params(relative, needle, occurrence, offset)
|
||||
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
record(phase="codeaction",
|
||||
row="%s (fan-out %d), %s" % (label, fanout, "lazy" if lazy else "eager"),
|
||||
ms=ms, n=result_count(message),
|
||||
titles=[a.get("title") for a in (message.get("result") or [])])
|
||||
with session("workspace", resolve_support=lazy) as s:
|
||||
settled(s)
|
||||
params = code_action_params(sites.TB, " // ", 1, 2)
|
||||
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
record(phase="codeaction", row="comment line, %s" % ("lazy" if lazy else "eager"),
|
||||
ms=ms, n=result_count(message))
|
||||
|
||||
|
||||
@phase("portaction")
|
||||
def phase_portaction():
|
||||
"""The one opentitan cursor that offers a port refactoring: offer + resolve."""
|
||||
for lazy in (True, False):
|
||||
with session("workspace", resolve_support=lazy) as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(sites.AES_WRAP))
|
||||
s.wait_quiet(0.6)
|
||||
s.take_notifications()
|
||||
params = code_action_params(sites.AES_WRAP, " aes #(", 1, 2)
|
||||
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
offered = message.get("result") or []
|
||||
record(phase="portaction",
|
||||
row="aes_wrap.sv offer, %s" % ("lazy" if lazy else "eager"),
|
||||
ms=ms, n=len(offered),
|
||||
titles=[a.get("title") for a in offered],
|
||||
has_edit=[("edit" in a) for a in offered])
|
||||
if lazy and offered:
|
||||
resolves = [s.ms("codeAction/resolve", offered[0])
|
||||
for _ in range(ARGS.tries + 1)]
|
||||
_, resolved = s.request("codeAction/resolve", offered[0])
|
||||
edit = (resolved.get("result") or {}).get("edit") or {}
|
||||
files = edit.get("changes") or {u: 1 for u in
|
||||
(c.get("textDocument", {}).get("uri")
|
||||
for c in edit.get("documentChanges") or [])}
|
||||
record(phase="portaction", row="aes_wrap.sv codeAction/resolve", ms=resolves,
|
||||
n=len(files), titles=[(resolved.get("result") or {}).get("title")])
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §6c / §49 — rename, and the hierarchical tail
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("rename")
|
||||
def phase_rename():
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
where = at(sites.TB, " aes #(", 1, 2)
|
||||
ms = tries(s, "textDocument/prepareRename", where, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/prepareRename", where)
|
||||
record(phase="rename", row="prepareRename on aes", ms=ms,
|
||||
note=json.dumps(message.get("result")))
|
||||
params = dict(where, newName="aes_renamed")
|
||||
ms = tries(s, "textDocument/rename", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/rename", params)
|
||||
record(phase="rename", row="rename aes -> aes_renamed", ms=ms,
|
||||
n=len(phases_new.edited_uris(message)))
|
||||
|
||||
|
||||
|
||||
@phase("blockers")
|
||||
def phase_blockers():
|
||||
leaders = [
|
||||
("codeAction on the aes token", "textDocument/codeAction",
|
||||
lambda: code_action_params(sites.TB, " aes #(", 1, 2)),
|
||||
("prepareRename on aes", "textDocument/prepareRename",
|
||||
lambda: at(sites.TB, " aes #(", 1, 2)),
|
||||
("rename on aes", "textDocument/rename",
|
||||
lambda: dict(at(sites.TB, " aes #(", 1, 2), newName="aes_renamed")),
|
||||
("workspace/symbol 'aes'", "workspace/symbol", lambda: {"query": "aes"}),
|
||||
]
|
||||
followers = [
|
||||
("definition", "textDocument/definition", lambda: at(sites.TB, " aes #(", 1, 2)),
|
||||
("hover", "textDocument/hover", lambda: at(sites.TB, " aes #(", 1, 2)),
|
||||
("documentSymbol", "textDocument/documentSymbol",
|
||||
lambda: {"textDocument": doc(sites.TB)}),
|
||||
]
|
||||
for row, method, make in leaders:
|
||||
own, behind = [], []
|
||||
for _ in range(ARGS.tries):
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
lead = s.send(method, make())
|
||||
ids = [(name, s.send(m, mk())) for name, m, mk in followers]
|
||||
own.append(s.await_id(lead)[0])
|
||||
behind.append([(name, s.await_id(rid)[0]) for name, rid in ids])
|
||||
record(phase="blockers", row=row, ms=own,
|
||||
note=" | ".join("; ".join("%s %.2f" % (n, v) for n, v in one)
|
||||
for one in behind))
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# §5 / §46 — the didOpen widen, and the didOpen delay
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("widen")
|
||||
def phase_widen():
|
||||
"""§5 — a `didOpen` that may widen the scope, then the request behind it.
|
||||
|
||||
One session per (scope, cache, try): the widen is a once-per-session event,
|
||||
so a second try inside the same session would measure nothing.
|
||||
"""
|
||||
for scope in ("depth0", "default"):
|
||||
for cache in ("cold", "warm"):
|
||||
runs = {relative: [] for relative in sites.WIDEN_FILES}
|
||||
seconds = {relative: [] for relative in sites.WIDEN_FILES}
|
||||
for _ in range(ARGS.tries):
|
||||
with session(scope, cold=(cache == "cold"),
|
||||
storage_name="widen-" + scope) as s:
|
||||
settled(s)
|
||||
for relative in sites.WIDEN_FILES:
|
||||
started = time.perf_counter()
|
||||
s.did_open(sites.path(relative))
|
||||
s.ms("textDocument/definition", at(relative, "module ", 1, 0))
|
||||
runs[relative].append((time.perf_counter() - started) * 1000.0)
|
||||
seconds[relative].append(
|
||||
s.ms("textDocument/definition", at(relative, "module ", 1, 0)))
|
||||
s.wait_quiet(0.5)
|
||||
s.take_notifications()
|
||||
for relative in sites.WIDEN_FILES:
|
||||
record(phase="widen",
|
||||
row="%s @ %s, %s" % (os.path.basename(relative), scope, cache),
|
||||
ms=runs[relative],
|
||||
note="second definition " + " / ".join(
|
||||
"%.2f" % v for v in seconds[relative]))
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# diagnostics, completion, hierarchy, RSS
|
||||
# =========================================================================
|
||||
|
||||
|
||||
@phase("diagnostics")
|
||||
def phase_diagnostics():
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read()
|
||||
runs = []
|
||||
for version in range(2, 2 + ARGS.tries + 1):
|
||||
s.take_notifications()
|
||||
started = time.perf_counter()
|
||||
s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version)
|
||||
while True:
|
||||
s.drain()
|
||||
if any(n["method"] == "textDocument/publishDiagnostics"
|
||||
for n in s.notifications):
|
||||
break
|
||||
if time.perf_counter() - started > 30:
|
||||
raise TimeoutError("no diagnostics published")
|
||||
time.sleep(0.001)
|
||||
runs.append((time.perf_counter() - started) * 1000.0)
|
||||
record(phase="diagnostics", row="publish after didChange (incl. ~150 ms debounce)",
|
||||
ms=runs)
|
||||
|
||||
|
||||
@phase("completion")
|
||||
def phase_completion():
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read()
|
||||
base = text.rstrip("\n")
|
||||
for version, prefix in enumerate(sites.COMPLETION_PREFIXES, start=2):
|
||||
body = base + "\n" + prefix + "\n"
|
||||
s.did_change(sites.path(sites.TB), body, version)
|
||||
where = {"textDocument": doc(sites.TB),
|
||||
"position": {"line": body.count("\n") - 1, "character": len(prefix)}}
|
||||
ms = tries(s, "textDocument/completion", where, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/completion", where)
|
||||
record(phase="completion", row="completion after %r" % prefix, ms=ms,
|
||||
n=result_count(message))
|
||||
|
||||
|
||||
@phase("probe")
|
||||
def phase_probe():
|
||||
"""Ad-hoc: what does a cursor offer? `--probe FILE:LINE:CHAR` (0-based)."""
|
||||
relative, line, character = ARGS.probe.rsplit(":", 2)
|
||||
where = {"line": int(line), "character": int(character)}
|
||||
with session("workspace", resolve_support=True) as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.8)
|
||||
s.take_notifications()
|
||||
params = {"textDocument": doc(relative), "range": {"start": where, "end": where},
|
||||
"context": {"diagnostics": []}}
|
||||
ms = tries(s, "textDocument/codeAction", params, 2)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
offered = message.get("result") or []
|
||||
record(phase="probe", row="%s %s:%s" % (relative, line, character), ms=ms,
|
||||
n=len(offered), titles=[a.get("title") for a in offered])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("phase", choices=sorted(harness.PHASES))
|
||||
parser.add_argument("--server", required=True)
|
||||
parser.add_argument("--label", required=True)
|
||||
parser.add_argument("--opentitan", default=sites.ROOT)
|
||||
parser.add_argument("--storage", required=True)
|
||||
parser.add_argument("--out", required=True)
|
||||
parser.add_argument("--tries", type=int, default=3)
|
||||
parser.add_argument("--probe", default="",
|
||||
help="for the `probe` phase: FILE:LINE:CHAR, 0-based")
|
||||
harness.configure(parser.parse_args())
|
||||
harness.PHASES[ARGS.phase]()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,128 @@
|
||||
"""What every phase shares: the registry, the session factory, the recorder.
|
||||
|
||||
`bench.py` owns the command line and the take-3 table's phases; `phases_new.py`
|
||||
owns the phases for what 0.44–0.49 added. Both import from here, so the run's
|
||||
configuration lives in exactly one place.
|
||||
|
||||
`ARGS` is a `Namespace` that is *mutated* by [`configure`], never rebound, so
|
||||
`from harness import ARGS` in another module keeps seeing the live values.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import sites
|
||||
from lspclient import Session, find_position, summarize, uri # noqa: F401
|
||||
|
||||
PHASES = {}
|
||||
|
||||
#: The run's configuration. Filled by `configure()`; never reassigned.
|
||||
ARGS = argparse.Namespace(
|
||||
server=None, label=None, opentitan=None, storage=None, out=None,
|
||||
tries=3, probe="",
|
||||
)
|
||||
|
||||
|
||||
def configure(parsed):
|
||||
"""Adopt a parsed command line, and point `sites` at the corpus."""
|
||||
for key, value in vars(parsed).items():
|
||||
setattr(ARGS, key, value)
|
||||
ARGS.opentitan = os.path.abspath(ARGS.opentitan)
|
||||
ARGS.out = os.path.abspath(ARGS.out)
|
||||
sites.ROOT = ARGS.opentitan
|
||||
os.makedirs(ARGS.storage, exist_ok=True)
|
||||
|
||||
|
||||
def phase(name):
|
||||
"""Register a phase under the name `bench.py <name>` runs."""
|
||||
|
||||
def register(fn):
|
||||
PHASES[name] = fn
|
||||
return fn
|
||||
|
||||
return register
|
||||
|
||||
|
||||
def record(**fields):
|
||||
"""Append one row to results.jsonl and echo it as a readable line."""
|
||||
fields.setdefault("ts", time.strftime("%Y-%m-%dT%H:%M:%S"))
|
||||
fields.setdefault("label", ARGS.label)
|
||||
with open(ARGS.out, "a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(fields) + "\n")
|
||||
ms = fields.get("ms")
|
||||
shown = " ".join("%.3f" % v for v in ms) if ms else ""
|
||||
print("%-11s %-52s %s %s" % (fields["phase"], fields.get("row", ""), shown,
|
||||
fields.get("note", "")), flush=True)
|
||||
|
||||
|
||||
def session(scope="workspace", cold=False, resolve_support=True, verbose=False,
|
||||
storage_name=None):
|
||||
"""A session at one scope, its index store under `--storage/<name>`.
|
||||
|
||||
Never the default store: the corpus must not be written near, and cache
|
||||
warmth has to be controllable per cell.
|
||||
"""
|
||||
store = os.path.join(ARGS.storage, storage_name or scope)
|
||||
return Session(
|
||||
server=ARGS.server,
|
||||
root=sites.ROOT,
|
||||
storage=store,
|
||||
scope=sites.SCOPES[scope],
|
||||
resolve_support=resolve_support,
|
||||
verbose=verbose,
|
||||
cold=cold,
|
||||
)
|
||||
|
||||
|
||||
def settled(s, open_file=sites.TB):
|
||||
"""Initialize, open a buffer, and wait for the scan to go quiet."""
|
||||
s.initialize()
|
||||
s.did_open(sites.path(open_file))
|
||||
s.wait_quiet(1.5)
|
||||
s.take_notifications()
|
||||
return s
|
||||
|
||||
|
||||
def tries(s, method, params, n=None):
|
||||
"""`n` identical requests; returns the millisecond list."""
|
||||
n = n or ARGS.tries
|
||||
return [s.ms(method, params) for _ in range(n)]
|
||||
|
||||
|
||||
def pos(relative, needle, occurrence=1, offset=0):
|
||||
"""0-based `{line, character}` of a token, resolved from the file text."""
|
||||
line, character = find_position(sites.path(relative), needle, occurrence, offset)
|
||||
return {"line": line, "character": character}
|
||||
|
||||
|
||||
def doc(relative):
|
||||
return {"uri": uri(sites.path(relative))}
|
||||
|
||||
|
||||
def at(relative, needle, occurrence=1, offset=0):
|
||||
"""A position request's params at a token."""
|
||||
return {"textDocument": doc(relative), "position": pos(relative, needle, occurrence, offset)}
|
||||
|
||||
|
||||
def code_action_params(relative, needle, occurrence=1, offset=0):
|
||||
"""A zero-width `textDocument/codeAction` range at a token."""
|
||||
where = pos(relative, needle, occurrence, offset)
|
||||
return {
|
||||
"textDocument": doc(relative),
|
||||
"range": {"start": where, "end": where},
|
||||
"context": {"diagnostics": []},
|
||||
}
|
||||
|
||||
|
||||
def result_count(message):
|
||||
"""How many things an answer carried — a list, an item list, or one thing."""
|
||||
result = message.get("result")
|
||||
if result is None:
|
||||
return 0
|
||||
if isinstance(result, list):
|
||||
return len(result)
|
||||
if isinstance(result, dict) and "items" in result:
|
||||
return len(result["items"])
|
||||
return 1
|
||||
@@ -0,0 +1,394 @@
|
||||
"""A minimal LSP client for the lucisv performance rounds.
|
||||
|
||||
Framed JSON-RPC over a `lucisv-server` child process's stdio. Python 3
|
||||
standard library only, no third-party packages, so it runs from a clean
|
||||
checkout with nothing installed.
|
||||
|
||||
What it does that a generic client does not, and why each exists:
|
||||
|
||||
- **The configuration pull is answered per session.** `lucisv-server` pulls
|
||||
`workspace/configuration` for the `lucisv` section; the index scope it gets
|
||||
back decides how many files are scanned, which is the single biggest lever
|
||||
on every number in a perf round. `Session(scope=...)` writes that reply.
|
||||
- **Client capabilities are settable per session.** A session that advertises
|
||||
`textDocument.codeAction.resolveSupport.properties: ["edit"]` gets the lazy
|
||||
`codeAction` offer (TODO §37.1); one that does not gets the eager shape.
|
||||
Both must be measurable from one harness.
|
||||
- **`storagePath` is always ours.** The index cache is directed at a scratch
|
||||
directory so cache warmth is controlled (delete it = cold) and so nothing
|
||||
is ever written near the corpus.
|
||||
- **`window/logMessage` is captured**, so a `--verbose` server's own
|
||||
`timing: <method> answered in <n> ms` lines can be read beside the wire.
|
||||
|
||||
Everything is timed with `time.perf_counter` from just before the write to
|
||||
just after the matching response is parsed: what an editor experiences.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
# The server's own timing line, from `--verbose` (docs/features/verbose-timing).
|
||||
TIMING_LINE = re.compile(r"timing: (\S+) answered in ([0-9.]+) ?ms")
|
||||
|
||||
|
||||
def uri(path):
|
||||
"""A `file://` URI for an absolute path, percent-encoding what LSP needs."""
|
||||
from urllib.parse import quote
|
||||
|
||||
return "file://" + quote(os.path.abspath(path))
|
||||
|
||||
|
||||
class Session:
|
||||
"""One `lucisv-server` process, driven over stdio.
|
||||
|
||||
Use as a context manager; the process is shut down and reaped on exit.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server,
|
||||
root,
|
||||
storage,
|
||||
scope=None,
|
||||
resolve_support=True,
|
||||
verbose=False,
|
||||
cold=False,
|
||||
guard=None,
|
||||
):
|
||||
self.server = server
|
||||
self.root = os.path.abspath(root)
|
||||
self.storage = os.path.abspath(storage)
|
||||
self.scope = scope if scope is not None else {}
|
||||
self.resolve_support = resolve_support
|
||||
self.verbose = verbose
|
||||
self.next_id = 1
|
||||
self.notifications = [] # every server->client notification, in order
|
||||
self.log_messages = [] # window/logMessage texts only
|
||||
self.timings = [] # (method, ms) from a --verbose server
|
||||
self.pending = {} # id -> (method, sent_at) for in-flight requests
|
||||
self.proc = None
|
||||
self._reader = None
|
||||
self._lock = threading.Lock()
|
||||
self._inbox = [] # parsed messages not yet consumed
|
||||
self._cond = threading.Condition(self._lock)
|
||||
self._cold = cold
|
||||
self._guard = guard or []
|
||||
|
||||
# -- lifecycle ---------------------------------------------------------
|
||||
|
||||
def __enter__(self):
|
||||
if self._cold:
|
||||
shutil.rmtree(self.storage, ignore_errors=True)
|
||||
os.makedirs(self.storage, exist_ok=True)
|
||||
cmd = list(self._guard) + [self.server]
|
||||
if self.verbose:
|
||||
cmd.append("--verbose")
|
||||
cmd.append("--stdio")
|
||||
self.proc = subprocess.Popen(
|
||||
cmd,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
self._reader = threading.Thread(target=self._read_loop, daemon=True)
|
||||
self._reader.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.close()
|
||||
return False
|
||||
|
||||
def close(self):
|
||||
if self.proc is None:
|
||||
return
|
||||
try:
|
||||
self.notify("exit", None)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.proc.stdin.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.proc.wait(timeout=10)
|
||||
except Exception:
|
||||
self.proc.kill()
|
||||
self.proc.wait()
|
||||
self.proc = None
|
||||
|
||||
# -- framing -----------------------------------------------------------
|
||||
|
||||
def _write(self, message):
|
||||
body = json.dumps(message).encode("utf-8")
|
||||
header = ("Content-Length: %d\r\n\r\n" % len(body)).encode("ascii")
|
||||
self.proc.stdin.write(header + body)
|
||||
self.proc.stdin.flush()
|
||||
|
||||
def _read_loop(self):
|
||||
stream = self.proc.stdout
|
||||
while True:
|
||||
length = None
|
||||
while True:
|
||||
line = stream.readline()
|
||||
if not line:
|
||||
return
|
||||
line = line.decode("utf-8", "replace").strip()
|
||||
if line == "":
|
||||
break
|
||||
if line.lower().startswith("content-length:"):
|
||||
length = int(line.split(":", 1)[1].strip())
|
||||
if length is None:
|
||||
continue
|
||||
payload = b""
|
||||
while len(payload) < length:
|
||||
chunk = stream.read(length - len(payload))
|
||||
if not chunk:
|
||||
return
|
||||
payload += chunk
|
||||
try:
|
||||
message = json.loads(payload.decode("utf-8"))
|
||||
except ValueError:
|
||||
continue
|
||||
self._dispatch(message)
|
||||
|
||||
def _dispatch(self, message):
|
||||
with self._cond:
|
||||
self._inbox.append(message)
|
||||
self._cond.notify_all()
|
||||
# Server->client requests must be answered from the reader thread, or
|
||||
# the server blocks and every timing after it is a lie.
|
||||
if "method" in message and "id" in message:
|
||||
self._answer_server_request(message)
|
||||
|
||||
def _answer_server_request(self, message):
|
||||
method = message["method"]
|
||||
if method == "workspace/configuration":
|
||||
items = message.get("params", {}).get("items", [])
|
||||
self._write(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": message["id"],
|
||||
"result": [self.scope for _ in items] or [self.scope],
|
||||
}
|
||||
)
|
||||
elif method in ("window/workDoneProgress/create", "client/registerCapability"):
|
||||
self._write({"jsonrpc": "2.0", "id": message["id"], "result": None})
|
||||
else:
|
||||
self._write({"jsonrpc": "2.0", "id": message["id"], "result": None})
|
||||
|
||||
# -- traffic -----------------------------------------------------------
|
||||
|
||||
def notify(self, method, params):
|
||||
self._write({"jsonrpc": "2.0", "method": method, "params": params})
|
||||
|
||||
def send(self, method, params):
|
||||
"""Send a request without waiting; returns its id (for pipelining)."""
|
||||
rid = self.next_id
|
||||
self.next_id += 1
|
||||
self.pending[rid] = (method, time.perf_counter())
|
||||
self._write({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
||||
return rid
|
||||
|
||||
def await_id(self, rid, timeout=300.0):
|
||||
"""Wait for the response to `rid`; returns (elapsed_ms, message)."""
|
||||
deadline = time.time() + timeout
|
||||
while True:
|
||||
with self._cond:
|
||||
for i, message in enumerate(self._inbox):
|
||||
if message.get("id") == rid and "method" not in message:
|
||||
self._inbox.pop(i)
|
||||
done = time.perf_counter()
|
||||
_, sent = self.pending.pop(rid)
|
||||
self._drain_locked()
|
||||
return (done - sent) * 1000.0, message
|
||||
self._drain_locked()
|
||||
remaining = deadline - time.time()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("no response to request %d" % rid)
|
||||
self._cond.wait(min(remaining, 0.05))
|
||||
|
||||
def request(self, method, params, timeout=300.0):
|
||||
"""Send and wait. Returns (elapsed_ms, result_or_error_message)."""
|
||||
return self.await_id(self.send(method, params), timeout)
|
||||
|
||||
def ms(self, method, params, timeout=300.0):
|
||||
"""Just the round trip in milliseconds."""
|
||||
return self.request(method, params, timeout)[0]
|
||||
|
||||
# -- notification bookkeeping -----------------------------------------
|
||||
|
||||
def _drain_locked(self):
|
||||
"""Move server notifications out of the inbox into the log."""
|
||||
kept = []
|
||||
for message in self._inbox:
|
||||
if "method" in message and "id" not in message:
|
||||
self.notifications.append(message)
|
||||
if message["method"] == "window/logMessage":
|
||||
text = message.get("params", {}).get("message", "")
|
||||
self.log_messages.append(text)
|
||||
found = TIMING_LINE.search(text)
|
||||
if found:
|
||||
self.timings.append((found.group(1), float(found.group(2))))
|
||||
else:
|
||||
kept.append(message)
|
||||
self._inbox[:] = kept
|
||||
|
||||
def drain(self):
|
||||
with self._cond:
|
||||
self._drain_locked()
|
||||
|
||||
def wait_quiet(self, quiet=1.5, timeout=300.0):
|
||||
"""Block until no notification has arrived for `quiet` seconds.
|
||||
|
||||
The scan's end is not one message: `$/progress` `end` can be followed
|
||||
by more indexing chatter, so silence is the reliable barrier. Returns
|
||||
the seconds from entry to the last notification seen.
|
||||
"""
|
||||
started = time.perf_counter()
|
||||
last = time.perf_counter()
|
||||
seen = len(self.notifications)
|
||||
deadline = time.time() + timeout
|
||||
while True:
|
||||
self.drain()
|
||||
if len(self.notifications) != seen:
|
||||
seen = len(self.notifications)
|
||||
last = time.perf_counter()
|
||||
if time.perf_counter() - last >= quiet:
|
||||
return (last - started) * 1000.0
|
||||
if time.time() > deadline:
|
||||
raise TimeoutError("server never went quiet")
|
||||
time.sleep(0.005)
|
||||
|
||||
def take_notifications(self, method=None):
|
||||
"""Consume and return the notifications logged so far."""
|
||||
self.drain()
|
||||
found = [n for n in self.notifications if method is None or n["method"] == method]
|
||||
self.notifications = []
|
||||
return found
|
||||
|
||||
def take_timings(self, method=None):
|
||||
self.drain()
|
||||
found = [t for t in self.timings if method is None or t[0] == method]
|
||||
self.timings = []
|
||||
return found
|
||||
|
||||
# -- protocol shortcuts ------------------------------------------------
|
||||
|
||||
def capabilities(self):
|
||||
"""The client capabilities this session advertises."""
|
||||
code_action = {
|
||||
"codeActionLiteralSupport": {
|
||||
"codeActionKind": {"valueSet": ["", "quickfix", "refactor", "source"]}
|
||||
},
|
||||
"dataSupport": True,
|
||||
}
|
||||
if self.resolve_support:
|
||||
code_action["resolveSupport"] = {"properties": ["edit"]}
|
||||
return {
|
||||
"workspace": {
|
||||
"configuration": True,
|
||||
"workspaceEdit": {"documentChanges": True},
|
||||
"symbol": {"dynamicRegistration": False},
|
||||
"didChangeConfiguration": {"dynamicRegistration": False},
|
||||
},
|
||||
"textDocument": {
|
||||
"synchronization": {"dynamicRegistration": False},
|
||||
"codeAction": code_action,
|
||||
"completion": {"completionItem": {"snippetSupport": True}},
|
||||
"hover": {"contentFormat": ["markdown", "plaintext"]},
|
||||
"rename": {"prepareSupport": True},
|
||||
"publishDiagnostics": {"relatedInformation": True},
|
||||
"semanticTokens": {
|
||||
"requests": {"full": True},
|
||||
"tokenTypes": [],
|
||||
"tokenModifiers": [],
|
||||
"formats": ["relative"],
|
||||
},
|
||||
"inlayHint": {"dynamicRegistration": False},
|
||||
},
|
||||
"window": {"workDoneProgress": True},
|
||||
}
|
||||
|
||||
def initialize(self):
|
||||
"""`initialize` + `initialized`; returns the request's milliseconds."""
|
||||
params = {
|
||||
"processId": os.getpid(),
|
||||
"rootUri": uri(self.root),
|
||||
"capabilities": self.capabilities(),
|
||||
"initializationOptions": {"storagePath": self.storage},
|
||||
"workspaceFolders": [{"uri": uri(self.root), "name": "opentitan"}],
|
||||
}
|
||||
elapsed, _ = self.request("initialize", params)
|
||||
self.notify("initialized", {})
|
||||
return elapsed
|
||||
|
||||
def did_open(self, path, language="systemverilog"):
|
||||
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
||||
text = handle.read()
|
||||
self.notify(
|
||||
"textDocument/didOpen",
|
||||
{
|
||||
"textDocument": {
|
||||
"uri": uri(path),
|
||||
"languageId": language,
|
||||
"version": 1,
|
||||
"text": text,
|
||||
}
|
||||
},
|
||||
)
|
||||
return text
|
||||
|
||||
def did_change(self, path, text, version=2):
|
||||
self.notify(
|
||||
"textDocument/didChange",
|
||||
{
|
||||
"textDocument": {"uri": uri(path), "version": version},
|
||||
"contentChanges": [{"text": text}],
|
||||
},
|
||||
)
|
||||
|
||||
def at(self, path, line, character, method, extra=None):
|
||||
"""A position request's params, 0-based line and UTF-16 character."""
|
||||
params = {
|
||||
"textDocument": {"uri": uri(path)},
|
||||
"position": {"line": line, "character": character},
|
||||
}
|
||||
if extra:
|
||||
params.update(extra)
|
||||
return method, params
|
||||
|
||||
|
||||
def find_position(path, needle, occurrence=1, offset=0):
|
||||
"""0-based (line, character) of the `occurrence`th `needle` in a file.
|
||||
|
||||
Positions are resolved from the text at run time rather than hard-coded,
|
||||
so a corpus that moves by a line does not silently measure the wrong
|
||||
token. `offset` shifts the character within the match.
|
||||
"""
|
||||
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
||||
seen = 0
|
||||
for number, line in enumerate(handle):
|
||||
start = 0
|
||||
while True:
|
||||
found = line.find(needle, start)
|
||||
if found < 0:
|
||||
break
|
||||
seen += 1
|
||||
if seen == occurrence:
|
||||
return number, found + offset
|
||||
start = found + 1
|
||||
raise LookupError("%r not found %dx in %s" % (needle, occurrence, path))
|
||||
|
||||
|
||||
def summarize(values):
|
||||
"""(first, min_of_repeats, max_of_repeats) from a try list."""
|
||||
if not values:
|
||||
return None, None, None
|
||||
if len(values) == 1:
|
||||
return values[0], values[0], values[0]
|
||||
return values[0], min(values[1:]), max(values[1:])
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# The per-file outcome runs, for the release-to-release outcome diff.
|
||||
#
|
||||
# tools/perf/outcomes.sh <lucisv-binary> <label> <opentitan-dir> <out-dir>
|
||||
#
|
||||
# `format --check --no-cache` and `check` over the five trees, with every
|
||||
# per-file line kept. `--no-cache` so the verdict is computed, never recalled,
|
||||
# and so the two binaries are compared on the same work. Paths are rewritten
|
||||
# relative to the corpus root, so two runs differ only where an *outcome* did.
|
||||
#
|
||||
# Writes `<out-dir>/<label>.format.txt`, `<label>.check.txt`,
|
||||
# `<label>.check-select.txt`. Diff two labels with:
|
||||
#
|
||||
# diff <out-dir>/0.43.0.format.txt <out-dir>/0.49.0.format.txt
|
||||
#
|
||||
# Untimed — correctness, not timing — so it is safe to run beside other work.
|
||||
# Still guarded, like every `lucisv` invocation in this round.
|
||||
set -u
|
||||
|
||||
BIN=${1:?usage: outcomes.sh <binary> <label> <opentitan> <outdir>}
|
||||
LABEL=${2:?}
|
||||
OT=${3:?}
|
||||
OUT=${4:?}
|
||||
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
GUARD="$HERE/../guard.sh"
|
||||
TREES="hw/ip hw/top_earlgrey/ip hw/top_darjeeling/ip hw/dv hw/vendor"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
|
||||
emit() {
|
||||
local suffix=$1
|
||||
shift
|
||||
local out="$OUT/${LABEL}.${suffix}.txt"
|
||||
: >"$out"
|
||||
for tree in $TREES; do
|
||||
echo "=== $tree ===" >>"$out"
|
||||
"$GUARD" -m 8 -t 1800 -- "$BIN" "$@" "$OT/$tree" 2>&1 |
|
||||
sed "s#$OT/##g" |
|
||||
LC_ALL=C sort >>"$out"
|
||||
done
|
||||
echo "wrote $out"
|
||||
}
|
||||
|
||||
emit format format --no-cache --check
|
||||
emit check check
|
||||
emit check-select check --select error,warning,style
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The phases for what 0.44–0.49 added: the new offer sites, §49's
|
||||
hierarchical surface, §46's `didOpen` fix on the wire, `lucisv/moduleHierarchy`
|
||||
and the index's cost on disk and in memory.
|
||||
|
||||
Imported by `bench.py`, which owns the registry and the command line; nothing
|
||||
here is run directly. Split out of `bench.py` so each file stays inside
|
||||
CLAUDE.md's size rule and each has one sentence: `bench.py` is the take-3
|
||||
table, this is what changed since it.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from harness import (
|
||||
ARGS, Session, at, code_action_params, doc, phase, pos, record,
|
||||
result_count, session, settled, sites, tries,
|
||||
)
|
||||
|
||||
|
||||
@phase("refactor")
|
||||
def phase_refactor():
|
||||
"""The offer sites 0.44–0.49 added: what is offered, and what it costs."""
|
||||
for label, relative, needle, occurrence, offset in sites.REFACTOR_SITES:
|
||||
with session("workspace", resolve_support=True) as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.6)
|
||||
s.take_notifications()
|
||||
params = code_action_params(relative, needle, occurrence, offset)
|
||||
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
offered = message.get("result") or []
|
||||
record(phase="refactor", row="%s offer" % label, ms=ms, n=len(offered),
|
||||
titles=[a.get("title") for a in offered],
|
||||
file=relative, position=params["range"]["start"])
|
||||
for action in offered:
|
||||
if "edit" in action:
|
||||
continue
|
||||
resolves = [s.ms("codeAction/resolve", action) for _ in range(ARGS.tries + 1)]
|
||||
_, resolved = s.request("codeAction/resolve", action)
|
||||
edit = (resolved.get("result") or {}).get("edit") or {}
|
||||
record(phase="refactor", row="%s resolve: %s" % (label, action.get("title")),
|
||||
ms=resolves, n=len(edit.get("changes") or
|
||||
edit.get("documentChanges") or []))
|
||||
# `extract module` is a selection, not a point.
|
||||
relative, first, first_n, last, last_n = sites.EXTRACT_SELECTION
|
||||
start = pos(relative, first, first_n)
|
||||
end = pos(relative, last, last_n)
|
||||
end = {"line": end["line"], "character": end["character"] + len(last)}
|
||||
with session("workspace", resolve_support=True) as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.6)
|
||||
s.take_notifications()
|
||||
params = {"textDocument": doc(relative),
|
||||
"range": {"start": start, "end": end},
|
||||
"context": {"diagnostics": []}}
|
||||
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/codeAction", params)
|
||||
offered = message.get("result") or []
|
||||
record(phase="refactor", row="extract-module offer (selection)", ms=ms, n=len(offered),
|
||||
titles=[a.get("title") for a in offered], file=relative,
|
||||
position=start, note="selection %d:%d-%d:%d" % (
|
||||
start["line"], start["character"], end["line"], end["character"]))
|
||||
for action in offered:
|
||||
if "edit" in action:
|
||||
continue
|
||||
resolves = [s.ms("codeAction/resolve", action) for _ in range(ARGS.tries + 1)]
|
||||
record(phase="refactor", row="extract-module resolve: %s" % action.get("title"),
|
||||
ms=resolves)
|
||||
|
||||
|
||||
@phase("tailrename")
|
||||
def phase_tailrename():
|
||||
"""§49 — a net renamed at its declaration, named through an instance tail."""
|
||||
relative, needle, occurrence, offset = sites.TAIL_RENAME
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.did_open(sites.path(sites.TAIL_TAIL_FILE))
|
||||
s.wait_quiet(0.8)
|
||||
s.take_notifications()
|
||||
where = at(relative, needle, occurrence, offset)
|
||||
record(phase="tailrename", row="tail rename cursor", ms=[0.0],
|
||||
note=json.dumps(where["position"]), file=relative)
|
||||
params = dict(where, newName="state_q_x")
|
||||
ms = tries(s, "textDocument/rename", params, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/rename", params)
|
||||
uris = edited_uris(message)
|
||||
tail = os.path.basename(sites.TAIL_TAIL_FILE)
|
||||
record(phase="tailrename",
|
||||
row="rename state_q (tail through u_entropy_src_main_sm)",
|
||||
ms=ms, n=len(uris),
|
||||
note="tail edited" if any(tail in u for u in uris) else "TAIL NOT EDITED",
|
||||
titles=sorted(os.path.basename(u) for u in uris))
|
||||
|
||||
def edited_uris(message):
|
||||
"""The URIs a `WorkspaceEdit` touches, whichever shape it came in."""
|
||||
edit = message.get("result") or {}
|
||||
if not isinstance(edit, dict):
|
||||
return []
|
||||
if edit.get("changes"):
|
||||
return list(edit["changes"].keys())
|
||||
return [c.get("textDocument", {}).get("uri", "")
|
||||
for c in edit.get("documentChanges") or []]
|
||||
|
||||
|
||||
@phase("didopen")
|
||||
def phase_didopen():
|
||||
"""§46 — `didOpen` → the request behind it, workspace scope, warm store."""
|
||||
for relative in sites.DIDOPEN_FILES:
|
||||
runs, seconds = [], []
|
||||
for _ in range(ARGS.tries):
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
started = time.perf_counter()
|
||||
s.did_open(sites.path(relative))
|
||||
s.ms("textDocument/definition", at(relative, "module ", 1, 0))
|
||||
runs.append((time.perf_counter() - started) * 1000.0)
|
||||
seconds.append(s.ms("textDocument/definition", at(relative, "module ", 1, 0)))
|
||||
lines = sum(1 for _ in open(sites.path(relative), encoding="utf-8", errors="replace"))
|
||||
record(phase="didopen", row="didOpen %s -> definition" % os.path.basename(relative),
|
||||
ms=runs, n=lines,
|
||||
note="second definition " + " / ".join("%.2f" % v for v in seconds))
|
||||
|
||||
|
||||
@phase("tailcompletion")
|
||||
def phase_tailcompletion():
|
||||
"""Completion after `u_x.` on an instance head (§49's surface)."""
|
||||
relative, needle, occurrence, offset = sites.TAIL_HEAD_COMPLETION
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
s.did_open(sites.path(relative))
|
||||
s.wait_quiet(0.8)
|
||||
s.take_notifications()
|
||||
where = at(relative, needle, occurrence, offset)
|
||||
ms = tries(s, "textDocument/completion", where, ARGS.tries + 1)
|
||||
_, message = s.request("textDocument/completion", where)
|
||||
items = (message.get("result") or {})
|
||||
items = items.get("items", items) if isinstance(items, dict) else items
|
||||
record(phase="tailcompletion",
|
||||
row="completion after an instance head + '.' (%s)" % os.path.basename(
|
||||
sites.path(relative)),
|
||||
ms=ms, n=result_count(message),
|
||||
titles=[i.get("label") for i in (items or [])[:8]])
|
||||
|
||||
|
||||
@phase("hierarchy")
|
||||
def phase_hierarchy():
|
||||
with session("workspace") as s:
|
||||
settled(s)
|
||||
ms = tries(s, "lucisv/moduleHierarchy", {}, ARGS.tries + 1)
|
||||
_, message = s.request("lucisv/moduleHierarchy", {})
|
||||
result = message.get("result") or {}
|
||||
payload = len(json.dumps(result))
|
||||
record(phase="hierarchy", row="lucisv/moduleHierarchy", ms=ms, n=payload,
|
||||
note="modules %d, files %d, schema %s" % (
|
||||
len(result.get("modules") or []), len(result.get("files") or []),
|
||||
result.get("schemaVersion")))
|
||||
|
||||
|
||||
@phase("rss")
|
||||
def phase_rss():
|
||||
"""Server peak RSS after the workspace scan, and the index store on disk.
|
||||
|
||||
RSS is read with `ps -o rss=` on the server's own pid a second after the
|
||||
scan settles, so it is the resident set of a server that has finished
|
||||
indexing and is idle — what an editor session actually holds.
|
||||
"""
|
||||
store = os.path.join(ARGS.storage, "rss")
|
||||
for cache in ("cold", "warm"):
|
||||
rss, size = [], "0"
|
||||
for _ in range(ARGS.tries):
|
||||
s = Session(server=ARGS.server, root=sites.ROOT, storage=store,
|
||||
scope=sites.SCOPES["workspace"], cold=(cache == "cold"))
|
||||
with s:
|
||||
settled(s)
|
||||
time.sleep(1.0)
|
||||
rss.append(float(subprocess.run(
|
||||
["ps", "-o", "rss=", "-p", str(s.proc.pid)],
|
||||
capture_output=True, text=True).stdout.strip()))
|
||||
size = subprocess.run(["du", "-sk", store], capture_output=True,
|
||||
text=True).stdout.split()[0]
|
||||
record(phase="rss", row="server RSS after workspace scan, %s cache" % cache,
|
||||
ms=rss, n=int(size),
|
||||
note="RSS KB above; index store %s KB" % size)
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""The opentitan positions every perf phase measures, resolved at run time.
|
||||
|
||||
Nothing here is a hard-coded line number: each site names the *text* it wants
|
||||
and `lspclient.find_position` locates it when the phase runs, so a corpus that
|
||||
moves by a line measures the same token rather than a silent neighbour. The
|
||||
0-based positions in `docs/performance_take4.md` are what these resolve to on
|
||||
opentitan `0098135264`.
|
||||
|
||||
`ROOT` is overridden by `bench.py --opentitan`; every path below hangs off it.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
ROOT = os.environ.get("OPENTITAN", "/Users/guoliangchen/repo/opentitan")
|
||||
|
||||
|
||||
def path(relative):
|
||||
return os.path.join(ROOT, relative)
|
||||
|
||||
|
||||
# -- the take-3 scenario files ---------------------------------------------
|
||||
|
||||
TB = "hw/ip/aes/dv/tb/tb.sv"
|
||||
AES = "hw/ip/aes/rtl/aes.sv"
|
||||
AES_CORE = "hw/ip/aes/rtl/aes_core.sv"
|
||||
AES_WRAP = "hw/ip/aes/rtl/aes_wrap.sv"
|
||||
AON_TIMER = "hw/ip/aon_timer/rtl/aon_timer.sv"
|
||||
KMAC = "hw/ip/kmac/rtl/kmac.sv"
|
||||
HMAC = "hw/ip/hmac/rtl/hmac.sv"
|
||||
SPI_DEVICE = "hw/ip/spi_device/rtl/spi_device.sv"
|
||||
PINMUX_REG_TOP = "hw/top_darjeeling/ip_autogen/pinmux/rtl/pinmux_reg_top.sv"
|
||||
AES_BIND = "hw/ip/aes/dv/sva/aes_bind.sv"
|
||||
ENTROPY_SRC_CORE = "hw/ip/entropy_src/rtl/entropy_src_core.sv"
|
||||
ENTROPY_SRC_SM = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv"
|
||||
SHA3_FPV = "hw/ip/kmac/fpv/tb/sha3_fpv.sv"
|
||||
AES_SBOX_MASKED = "hw/ip/aes/rtl/aes_sbox_canright_masked.sv"
|
||||
|
||||
# The take-3 `codeAction` cursors:
|
||||
# (label, file, needle, occurrence, fan-out, cursor offset into the needle).
|
||||
# The cursor lands on the module name. The fan-out is
|
||||
# `grep -rlE '^\s*<module>( |#|$)' --include='*.sv'` over the corpus,
|
||||
# re-derived for take 4 and identical to take 3's (1 / 6 / 42 / 67 / 128).
|
||||
# The fan-out is `grep -rlE '^\s*<module>( |#|$)' --include='*.sv'` over the
|
||||
# tree, re-derived for take 4 and identical to take 3's (1 / 6 / 42 / 67 / 128).
|
||||
FANOUT_CURSORS = [
|
||||
("aes_reg_top", AES, "aes_reg_top u_reg (", 1, 1, 0),
|
||||
("aes", TB, " aes #(", 1, 6, 2),
|
||||
("prim_lc_sync", AES, "prim_lc_sync #(", 1, 42, 0),
|
||||
("prim_alert_sender", AES, "prim_alert_sender #(", 1, 67, 0),
|
||||
("prim_flop_2sync", AON_TIMER, "prim_flop_2sync #(", 1, 128, 0),
|
||||
]
|
||||
|
||||
# The scope replies handed back to `workspace/configuration`, by name.
|
||||
SCOPES = {
|
||||
"default": {},
|
||||
"empty-index": {"index": {}},
|
||||
"depth0": {"index": {"scopeDepth": 0}},
|
||||
"workspace": {"index": {"scope": "workspace"}},
|
||||
}
|
||||
|
||||
# Files opened one at a time in the widen phases (§5), with their sizes.
|
||||
WIDEN_FILES = [AES, KMAC, HMAC, SPI_DEVICE]
|
||||
|
||||
# §46's didOpen → next-request files, the perf README's 2026-09-05 set.
|
||||
DIDOPEN_FILES = [AES, AES_CORE, SPI_DEVICE, PINMUX_REG_TOP]
|
||||
|
||||
# The five refactoring offer sites 0.44–0.49 added, each a real opentitan
|
||||
# position. `kind` names the action the site is meant to raise; the phase
|
||||
# records what is actually offered, which is the point of measuring it.
|
||||
# Each site was found by sweeping every instantiation-shaped and `import` line
|
||||
# in a set of RTL files and keeping the positions that actually offer (the
|
||||
# sweep is `bench.py probe`, one cursor at a time). The 0-based positions these
|
||||
# resolve to on opentitan `0098135264` are named in `docs/performance_take4.md`
|
||||
# §6b. There is **no** `convert to ANSI` site: opentitan has zero non-ANSI
|
||||
# module headers (§6b), so the last row measures an ANSI header, where the
|
||||
# action is correctly not offered.
|
||||
REFACTOR_SITES = [
|
||||
# A wildcard connection: `sha3 #(.EnMasking(...)) u_sha3 ( .* );` → 54:4.
|
||||
("expand-wildcard", SHA3_FPV, " ) u_sha3 (", 1, 4),
|
||||
# Two imports, one unused and one out of order → 42:2.
|
||||
("organize-imports", AES_SBOX_MASKED, " import aes_pkg::*;", 1, 2),
|
||||
# A separate-file instance written with named connections → 66:2.
|
||||
("inline-module", AES_WRAP, " tlul_cmd_intg_gen tlul_cmd_intg_gen (", 1, 2),
|
||||
# The take-3 offer site, still the one port-refactoring cursor found → 78:2.
|
||||
("port-actions", AES_WRAP, " aes #(", 1, 2),
|
||||
# An ANSI module header: the contrast row for `convert to ANSI` → 8:0.
|
||||
("ansi-header (no offer expected)", AES, "module aes", 1, 0),
|
||||
]
|
||||
|
||||
# The `extract module` site is a *selection*, not a point: three contiguous
|
||||
# whole module items — `aes.sv`'s three status `assign`s. The span runs from
|
||||
# the first needle's start to the end of the second needle.
|
||||
EXTRACT_SELECTION = (
|
||||
AES,
|
||||
" assign idle_o", 1,
|
||||
" assign input_ready_o = reg2hw.status.input_ready.q;", 1,
|
||||
)
|
||||
|
||||
# §49's hierarchical tail. `entropy_src_main_sm.sv` declares `state_q` — a
|
||||
# variable, not a port, so only the *hierarchical* surface reaches it — and
|
||||
# `entropy_src_core.sv` instantiates that module as `u_entropy_src_main_sm`
|
||||
# and names `u_entropy_src_main_sm.state_q`. The rename is issued at the
|
||||
# declaration; the row records whether the tail's file joins the edit set,
|
||||
# which is exactly what §49 changed.
|
||||
TAIL_RENAME = (ENTROPY_SRC_SM, "state_d, state_q;", 1, len("state_d, "))
|
||||
TAIL_TAIL_FILE = ENTROPY_SRC_CORE
|
||||
TAIL_HEAD_COMPLETION = (
|
||||
ENTROPY_SRC_CORE,
|
||||
"u_entropy_src_main_sm.state_q", 1, len("u_entropy_src_main_sm."),
|
||||
)
|
||||
|
||||
# The completion prefixes of take 3 §6d, typed at a fresh line in `tb.sv`.
|
||||
COMPLETION_PREFIXES = ["", "a", "ae", "aes", "aes_", "prim_", "clk", "aes_reg", "zzzz"]
|
||||
|
||||
# The five CLI sweep trees (`sweep.sh` reads the same list).
|
||||
TREES = [
|
||||
"hw/ip",
|
||||
"hw/top_earlgrey/ip",
|
||||
"hw/top_darjeeling/ip",
|
||||
"hw/dv",
|
||||
"hw/vendor",
|
||||
]
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# The timed CLI sweeps: `format --check` (cold and warm cache) and `check`
|
||||
# (default rules, and `--select error,warning,style`) over five opentitan
|
||||
# trees, one binary at a time, three tries per cell, wall clock and peak RSS
|
||||
# from `/usr/bin/time -l`.
|
||||
#
|
||||
# tools/perf/sweep.sh <lucisv-binary> <label> <opentitan-dir> <out-dir> [tries]
|
||||
#
|
||||
# Each cell writes `<out-dir>/<label>__<tree>__<command>__<cache>.txt`, which
|
||||
# holds the three runs' `/usr/bin/time -l` blocks; `sweeptable.py` reads them.
|
||||
# The formatter cache is a scratch `--cache-dir` under `<out-dir>`, so nothing
|
||||
# is ever written into the corpus.
|
||||
#
|
||||
# Every `lucisv` invocation goes through `tools/guard.sh -m 8 -t 1800`.
|
||||
set -u
|
||||
|
||||
BIN=${1:?usage: sweep.sh <binary> <label> <opentitan> <outdir> [tries]}
|
||||
LABEL=${2:?}
|
||||
OT=${3:?}
|
||||
OUT=${4:?}
|
||||
TRIES=${5:-3}
|
||||
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
GUARD="$HERE/../guard.sh"
|
||||
CACHE="$OUT/fmtcache"
|
||||
|
||||
TREES="hw/ip hw/top_earlgrey/ip hw/top_darjeeling/ip hw/dv hw/vendor"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
|
||||
run_cell() {
|
||||
local tree=$1 name=$2 cache=$3
|
||||
shift 3
|
||||
local safe=${tree//\//_}
|
||||
local log="$OUT/${LABEL}__${safe}__${name}__${cache}.txt"
|
||||
: >"$log"
|
||||
if [ "$cache" = cold ]; then rm -rf "$CACHE"; fi
|
||||
local i
|
||||
for i in $(seq 1 "$TRIES"); do
|
||||
echo "--- try $i ---" >>"$log"
|
||||
# `-l` puts the resource block on stderr; both streams are kept.
|
||||
"$GUARD" -m 8 -t 1800 -- /usr/bin/time -l "$BIN" "$@" >>"$log" 2>>"$log"
|
||||
echo "--- exit $? ---" >>"$log"
|
||||
done
|
||||
echo "$log"
|
||||
}
|
||||
|
||||
for tree in $TREES; do
|
||||
echo "== $LABEL $tree"
|
||||
run_cell "$tree" format cold format --cache-dir "$CACHE" --check "$OT/$tree"
|
||||
run_cell "$tree" format warm format --cache-dir "$CACHE" --check "$OT/$tree"
|
||||
run_cell "$tree" check default check "$OT/$tree"
|
||||
run_cell "$tree" check select check --select error,warning,style "$OT/$tree"
|
||||
done
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Turn `sweep.sh`'s `/usr/bin/time -l` logs into the document's §7 table.
|
||||
|
||||
python3 tools/perf/sweeptable.py <out-dir> [--labels 0.49.0,0.43.0,0.39.0]
|
||||
|
||||
Reads every `<label>__<tree>__<command>__<cache>.txt` in `<out-dir>`, pulls the
|
||||
`real` seconds and the `maximum resident set size` out of each try's block, and
|
||||
prints a Markdown table with one row per (tree, command, cache) and one column
|
||||
per label — first try, then the range over the repeats, then peak RSS.
|
||||
|
||||
It also prints the summary line each run reported (`N files would be
|
||||
reformatted`, the finding count), because a timing that moved because the work
|
||||
moved is not a timing finding.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
REAL = re.compile(r"([0-9.]+)\s+real")
|
||||
RSS = re.compile(r"(\d+)\s+maximum resident set size")
|
||||
COMMANDS = [("format", "cold"), ("format", "warm"), ("check", "default"), ("check", "select")]
|
||||
COMMAND_NAMES = {
|
||||
("format", "cold"): "`format --check`, cold cache",
|
||||
("format", "warm"): "`format --check`, warm cache",
|
||||
("check", "default"): "`check` (default rules)",
|
||||
("check", "select"): "`check --select error,warning,style`",
|
||||
}
|
||||
TREES = ["hw/ip", "hw/top_earlgrey/ip", "hw/top_darjeeling/ip", "hw/dv", "hw/vendor"]
|
||||
|
||||
|
||||
def cell(directory, label, tree, command, cache):
|
||||
"""(reals, peak_rss_mb, summary_lines) for one cell, or None if absent."""
|
||||
name = "%s__%s__%s__%s.txt" % (label, tree.replace("/", "_"), command, cache)
|
||||
path = os.path.join(directory, name)
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
text = open(path, encoding="utf-8", errors="replace").read()
|
||||
reals = [float(v) for v in REAL.findall(text)]
|
||||
rss = [int(v) for v in RSS.findall(text)]
|
||||
# The run's own total line, not its per-file lines: a timing that moved
|
||||
# because the *work* moved is not a timing finding.
|
||||
summary = [
|
||||
line.strip()
|
||||
for line in text.splitlines()
|
||||
if re.match(r"^(\d+ files? would be reformatted|found \d+ violations|"
|
||||
r"no violations|All \d+)", line.strip())
|
||||
]
|
||||
return reals, (max(rss) / 1048576.0 if rss else 0.0), summary
|
||||
|
||||
|
||||
def render(reals):
|
||||
if not reals:
|
||||
return "—"
|
||||
if len(reals) == 1:
|
||||
return "%.2f" % reals[0]
|
||||
rest = reals[1:]
|
||||
if abs(max(rest) - min(rest)) < 0.005:
|
||||
return "%.2f / %.2f" % (reals[0], min(rest))
|
||||
return "%.2f / %.2f–%.2f" % (reals[0], min(rest), max(rest))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("directory")
|
||||
parser.add_argument("--labels", default="0.49.0,0.43.0,0.39.0")
|
||||
args = parser.parse_args()
|
||||
labels = args.labels.split(",")
|
||||
|
||||
print("| Tree | command | " + " | ".join(labels) + " | peak RSS (MB) |")
|
||||
print("|---|---|" + "---:|" * (len(labels) + 1))
|
||||
for tree in TREES:
|
||||
for command, cache in COMMANDS:
|
||||
cells = [cell(args.directory, label, tree, command, cache) for label in labels]
|
||||
if not any(cells):
|
||||
continue
|
||||
times = " | ".join(render(c[0]) if c else "—" for c in cells)
|
||||
rss = " → ".join("%.0f" % c[1] for c in cells if c)
|
||||
print("| `%s` | %s | %s | %s |" % (tree, COMMAND_NAMES[(command, cache)], times, rss))
|
||||
|
||||
print()
|
||||
print("Summary lines, per cell (what the run reported):")
|
||||
for tree in TREES:
|
||||
for command, cache in COMMANDS:
|
||||
for label in labels:
|
||||
found = cell(args.directory, label, tree, command, cache)
|
||||
if not found or not found[2]:
|
||||
continue
|
||||
print(" %-22s %-8s %-8s %-8s %s" % (
|
||||
tree, command, cache, label, found[2][0]))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user