Terminal feed: message-task yields, slices sized to speed, one show per frame

- On the web a turn yields through a MessageChannel task: a chain of
  zero-length timers is clamped to 4 ms each, which left the emulator
  idle for a third of a burst.
- Slices are cut to what the measured speed writes in the budget left,
  so a turn ends near 6 ms however costly the output is to parse; the
  first write takes 4 Ki units to measure.
- Writes no longer notify the view each: the feed shows the emulator's
  state once everything queued is written, and while output still waits
  after a turn at most every 32 ms, so a flood draws its final state per
  frame instead of a frame per turn.
- Stream bench: producer follows a flow window (256 KiB past drawn, 32 KiB
  frames, rate by elapsed time), reports time spent parsing, ?show=each
  for the old per-write notify; tool/perf/terminal_stream_profile.mjs
  prints a CPU profile of one workload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 02:52:41 +00:00
parent f7ef4d1445
commit ae07fe14db
8 changed files with 328 additions and 21 deletions
+41 -6
View File
@@ -6,7 +6,10 @@
// flutter build web --profile --target tool/perf/terminal_stream_bench.dart \
// --output build/terminal-bench
// Run with tool/perf/terminal_stream_bench.mjs, or open the page with
// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30` (the window size sets the grid).
// `?workload=seq|yes|unicode|colors|screen|progress&mb=30&rate=30&window=256`
// (the window size sets the grid; `rate` MB/s caps the producer and
// `window` KiB is how far it may run ahead of what is drawn, as the
// server's flow control, 0 for no limit).
// When the stream ends `window.__benchResult` holds a JSON summary:
// frames, build/raster/total quantiles (ms), rAF interval quantiles (ms),
// MB written, seconds and MB/s.
@@ -40,14 +43,27 @@ class _Bench extends StatefulWidget {
class _BenchState extends State<_Bench> {
late final Terminal _terminal = Terminal(maxLines: 10000);
// Wired as ChatShellTerminalSession wires its feed.
late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed(
(text, _) => _terminal.write(text),
(text, _) {
_parsing.start();
_terminal.write(text, notify: _notifyEachWrite);
_parsing.stop();
},
show: _notifyEachWrite ? null : _terminal.notifyListeners,
);
/// `?show=each`: every write notifies the view, as before frames were
/// coalesced.
bool get _notifyEachWrite => widget.params['show'] == 'each';
final List<FrameTiming> _timings = [];
final List<double> _intervals = [];
Duration? _lastFrame;
Timer? _producer;
final Stopwatch _clock = Stopwatch();
/// Time spent in the emulator's writes (parsing into the buffer).
final Stopwatch _parsing = Stopwatch();
int _written = 0;
int _counter = 0;
bool _done = false;
@@ -76,19 +92,35 @@ class _BenchState extends State<_Bench> {
_lastFrame = stamp;
}
/// KiB the producer may run ahead of what the feed has drawn, as the
/// server's flow window (256 KiB); 0 for no limit.
double get _window => double.tryParse(widget.params['window'] ?? '') ?? 256;
void _start() {
_clock.start();
// Every tick tops the output up to what the rate allows by now, at most
// a flow window past what is drawn: late ticks (a long frame) catch up,
// and a slow emulator holds the producer back as the server's flow
// control does.
const tick = Duration(milliseconds: 4);
final perTick = (_rate * 1e6 * tick.inMicroseconds / 1e6).round();
_producer = Timer.periodic(tick, (_) {
if (_written >= _megabytes * 1e6) {
_producer?.cancel();
_feed.then(_finish);
return;
}
final chunk = _chunk(perTick);
_written += chunk.length;
_feed.add(chunk, _written);
var allowed = _rate * 1e6 * _clock.elapsedMicroseconds / 1e6;
if (_window > 0) {
final ahead = _feed.drawn + _window * 1024;
if (ahead < allowed) allowed = ahead;
}
// In frames of at most 32 KiB, as the server sends a PTY's reads.
while (allowed - _written >= 1024) {
final size = allowed - _written;
final chunk = _chunk(size < 32768 ? size.round() : 32768);
_written += chunk.length;
_feed.add(chunk, _written);
}
});
}
@@ -164,6 +196,9 @@ class _BenchState extends State<_Bench> {
'mb': _written / 1e6,
'seconds': seconds,
'mbPerSecond': _written / 1e6 / seconds,
'parseSeconds': _parsing.elapsedMicroseconds / 1e6,
'parseMbPerSecond':
_written / 1e6 / (_parsing.elapsedMicroseconds / 1e6),
};
_benchResult = jsonEncode(result).toJS;
// ignore: avoid_print
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
// CPU profile of one terminal bench workload (tool/perf/terminal_stream_bench.dart)
// in headless Chrome: prints the functions with the most self and total
// time while the stream runs, and the bench's own summary line.
//
// node tool/perf/terminal_stream_profile.mjs --build build/terminal-bench \
// [--workload seq] [--mb 8] [--top 40] [--out profile.cpuprofile]
import { parseArgs } from 'node:util';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
import { openBrowser } from '../capture/browser.mjs';
import { serveBuild } from '../capture/serve.mjs';
const { values: options } = parseArgs({
options: {
build: { type: 'string' },
workload: { type: 'string', default: 'seq' },
mb: { type: 'string', default: '8' },
rate: { type: 'string', default: '30' },
top: { type: 'string', default: '40' },
out: { type: 'string' },
size: { type: 'string', default: '1280x800' },
},
});
if (!options.build) throw new Error('--build required');
const [width, height] = options.size.split('x').map(Number);
const server = await serveBuild(options.build);
const browser = await openBrowser();
const evaluate = async (expression) =>
(await browser.send('Runtime.evaluate', { expression, returnByValue: true })).result.value;
try {
await browser.send('Page.enable');
await browser.send('Runtime.enable');
await browser.send('Profiler.enable');
await browser.send('Profiler.setSamplingInterval', { interval: 200 });
await browser.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
const url = new URL('/', server.origin);
url.searchParams.set('workload', options.workload);
url.searchParams.set('mb', options.mb);
url.searchParams.set('rate', options.rate);
await browser.send('Page.navigate', { url: url.href });
// The bench streams 1.5 s after start-up; profile from then on.
await delay(1500);
await browser.send('Profiler.start');
let result = null;
for (let i = 0; i < 600 && !result; i++) {
await delay(250);
result = await evaluate('window.__benchResult ?? null');
}
const { profile } = await browser.send('Profiler.stop');
if (options.out) await writeFile(options.out, JSON.stringify(profile));
const byId = new Map(profile.nodes.map((n) => [n.id, n]));
const parent = new Map();
for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n.id);
const hits = new Map();
for (const s of profile.samples) hits.set(s, (hits.get(s) ?? 0) + 1);
const name = (n) => `${n.callFrame.functionName || '(anonymous)'} ${n.callFrame.url.split('/').pop()}:${n.callFrame.lineNumber}`;
const self = new Map();
const total = new Map();
let all = 0;
for (const [id, count] of hits) {
all += count;
const key = name(byId.get(id));
self.set(key, (self.get(key) ?? 0) + count);
const seen = new Set();
for (let at = id; at !== undefined; at = parent.get(at)) {
const k = name(byId.get(at));
if (seen.has(k)) continue;
seen.add(k);
total.set(k, (total.get(k) ?? 0) + count);
}
}
const pct = (v) => (100 * v / all).toFixed(1).padStart(5);
const top = Number(options.top);
console.log(`samples ${all}`);
console.log('--- self');
for (const [k, v] of [...self].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(v), pct(total.get(k)), k);
console.log('--- total');
for (const [k, v] of [...total].sort((a, b) => b[1] - a[1]).slice(0, top)) console.log(pct(self.get(k) ?? 0), pct(v), k);
console.log(result);
} finally {
await browser.close?.();
await server.close?.();
}