diff --git a/app/tool/perf/terminal_stream_bench.dart b/app/tool/perf/terminal_stream_bench.dart new file mode 100644 index 00000000..bd198076 --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.dart @@ -0,0 +1,199 @@ +// Terminal rendering bench: the app's emulator view (theme, text style and +// the sliced output feed the terminals use) streaming generated output at a +// fixed rate, with Flutter frame timings and rAF intervals recorded. +// +// Build (from app/): +// 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&mb=30&rate=30` (the window size sets the grid). +// 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. +import 'dart:async'; +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_feed.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_terminal_theme.dart'; +import 'package:xterm/xterm.dart'; + +@JS('__benchResult') +external set _benchResult(JSString value); + +void main() { + final params = Uri.base.queryParameters; + runApp(_Bench(params)); +} + +class _Bench extends StatefulWidget { + const _Bench(this.params); + + final Map params; + + @override + State<_Bench> createState() => _BenchState(); +} + +class _BenchState extends State<_Bench> { + late final Terminal _terminal = Terminal(maxLines: 10000); + late final ChatShellTerminalFeed _feed = ChatShellTerminalFeed( + (text, _) => _terminal.write(text), + ); + final List _timings = []; + final List _intervals = []; + Duration? _lastFrame; + Timer? _producer; + final Stopwatch _clock = Stopwatch(); + int _written = 0; + int _counter = 0; + bool _done = false; + + String get _workload => widget.params['workload'] ?? 'seq'; + double get _megabytes => double.tryParse(widget.params['mb'] ?? '') ?? 30; + double get _rate => double.tryParse(widget.params['rate'] ?? '') ?? 30; + + @override + void initState() { + super.initState(); + SchedulerBinding.instance.addTimingsCallback(_onTimings); + SchedulerBinding.instance.addPersistentFrameCallback(_onFrame); + // Let the first frames settle before streaming. + Timer(const Duration(milliseconds: 1500), _start); + } + + void _onTimings(List timings) { + if (_clock.isRunning) _timings.addAll(timings); + } + + void _onFrame(Duration stamp) { + if (_clock.isRunning && _lastFrame != null) { + _intervals.add((stamp - _lastFrame!).inMicroseconds / 1000); + } + _lastFrame = stamp; + } + + void _start() { + _clock.start(); + 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); + }); + } + + String _chunk(int size) { + final out = StringBuffer(); + while (out.length < size) { + _counter++; + switch (_workload) { + case 'yes': + out.write('y\r\n'); + case 'unicode': + out.write( + '$_counter é ñ 中文 😀 👍🏽 🇵🇹 │ ╭─╮ ▓▒░ \u{E0B0} done\r\n', + ); + case 'colors': + final c = 31 + _counter % 7; + out.write( + '\x1b[${c}m$_counter\x1b[0m \x1b[1mbold\x1b[0m ' + 'plain text line with some words\r\n', + ); + case 'screen': + // A full-screen program redrawing every row (top, an editor). + out.write('\x1b[H'); + for (var row = 0; row < 48; row++) { + final c = 31 + (row + _counter) % 7; + out.write( + '\x1b[${c}m${(_counter + row).toString().padLeft(8)}' + '\x1b[0m \x1b[7m cpu ${row % 100}% \x1b[0m ' + '${'process name and arguments ' * 4}\x1b[K\r\n', + ); + } + default: + out.write('$_counter\r\n'); + } + } + return out.toString(); + } + + void _finish() { + if (_done) return; + _done = true; + // A last frame flushes the engine's batched timings. + SchedulerBinding.instance.scheduleFrame(); + Timer(const Duration(milliseconds: 600), () { + _clock.stop(); + final seconds = _clock.elapsedMicroseconds / 1e6; + List ms(Duration Function(FrameTiming t) pick) => [ + for (final t in _timings) pick(t).inMicroseconds / 1000, + ]; + final result = { + 'workload': _workload, + 'frames': _timings.length, + 'build': _quantiles(ms((t) => t.buildDuration)), + 'raster': _quantiles(ms((t) => t.rasterDuration)), + 'total': _quantiles(ms((t) => t.totalSpan)), + 'interval': _quantiles(_intervals), + 'mb': _written / 1e6, + 'seconds': seconds, + 'mbPerSecond': _written / 1e6 / seconds, + }; + _benchResult = jsonEncode(result).toJS; + // ignore: avoid_print + print('BENCH_RESULT ${jsonEncode(result)}'); + }); + } + + static Map _quantiles(List values) { + if (values.isEmpty) return const {}; + final sorted = [...values]..sort(); + double at(double q) => + sorted[(q * (sorted.length - 1)).round().clamp(0, sorted.length - 1)]; + double round(double v) => (v * 100).roundToDouble() / 100; + return { + 'p50': round(at(0.5)), + 'p90': round(at(0.9)), + 'p99': round(at(0.99)), + 'max': round(sorted.last), + 'mean': round(sorted.reduce((a, b) => a + b) / sorted.length), + }; + } + + @override + void dispose() { + _producer?.cancel(); + _feed.dispose(); + SchedulerBinding.instance.removeTimingsCallback(_onTimings); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: ThemeData(brightness: Brightness.dark), + home: Builder( + builder: (context) => Scaffold( + body: TerminalView( + _terminal, + theme: chatShellTerminalTheme(context), + textStyle: chatShellTerminalStyle(context), + padding: const EdgeInsets.all(8), + readOnly: true, + ), + ), + ), + ); + } +} diff --git a/app/tool/perf/terminal_stream_bench.mjs b/app/tool/perf/terminal_stream_bench.mjs new file mode 100644 index 00000000..8f7bb6b1 --- /dev/null +++ b/app/tool/perf/terminal_stream_bench.mjs @@ -0,0 +1,72 @@ +#!/usr/bin/env node +// Streams generated output through the terminal bench build +// (tool/perf/terminal_stream_bench.dart) in headless Chrome and prints one +// JSON line per workload: Flutter frame build/raster quantiles, rAF +// intervals measured in the page, and the throughput reached. +// +// node tool/perf/terminal_stream_bench.mjs --build build/terminal-bench \ +// [--workloads seq,yes,unicode,colors,screen] [--mb 30] [--rate 30] [--size 1280x800] +import { parseArgs } from 'node:util'; +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' }, + workloads: { type: 'string', default: 'seq,yes,unicode,colors,screen' }, + mb: { type: 'string', default: '30' }, + rate: { type: 'string', default: '30' }, + size: { type: 'string', default: '1280x800' }, + timeout: { type: 'string', default: '120000' }, + }, +}); +if (!options.build) throw new Error('--build required'); +const [width, height] = options.size.split('x').map(Number); + +const quantiles = (values) => { + const sorted = [...values].sort((a, b) => a - b); + const at = (q) => sorted[Math.round(q * (sorted.length - 1))] ?? 0; + const r = (v) => Math.round(v * 100) / 100; + return { p50: r(at(0.5)), p90: r(at(0.9)), p99: r(at(0.99)), max: r(sorted.at(-1) ?? 0) }; +}; + +const server = await serveBuild(options.build); +const browser = await openBrowser(); +const evaluate = async (expression) => { + const r = await browser.send('Runtime.evaluate', { expression, returnByValue: true }); + return r.result.value; +}; +try { + await browser.send('Page.enable'); + await browser.send('Runtime.enable'); + for (const workload of options.workloads.split(',')) { + const url = new URL('/', server.origin); + url.searchParams.set('workload', workload); + url.searchParams.set('mb', options.mb); + url.searchParams.set('rate', options.rate); + await browser.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); + await browser.send('Page.navigate', { url: url.href }); + await delay(300); + await evaluate(`(() => { + window.__raf = []; + let last = performance.now(); + const tick = (t) => { window.__raf.push(t - last); last = t; if (!window.__benchResult) requestAnimationFrame(tick); }; + requestAnimationFrame(tick); + return true; + })()`); + const deadline = Date.now() + Number(options.timeout); + let result = null; + while (!result && Date.now() < deadline) { + await delay(500); + result = await evaluate('window.__benchResult ?? null'); + } + if (!result) throw new Error(`${workload}: no result before the timeout`); + const raf = await evaluate('window.__raf'); + // Skip the start-up frames before streaming starts. + console.log(JSON.stringify({ ...JSON.parse(result), pageRaf: quantiles(raf.slice(50)) })); + } +} finally { + await browser.close?.(); + await server.close?.(); +}