#!/usr/bin/env python3 """What the line editor costs: start to first prompt, then one key. bench/editor.py ./zash dash bash [more shells ...] Each shell is started BENCH_N times (default 20) on a pseudo-terminal, the wall clock is read from just before the fork to the first byte of the prompt, and then BENCH_KEYS keys (default 200) are typed one at a time, timing each write to its echo. The median of each is reported. The fork itself is part of the start figure for every shell, so the comparison is fair, but the absolute column is a little high. A key's round trip is dominated by the terminal driver and the scheduler, which both shells pay alike; what the numbers separate is the editor's own work on each key. """ import fcntl import os import pty import select import statistics import struct import sys import termios import time from contextlib import suppress def env_int(name, default): """A count from the environment, or the default.""" value = os.environ.get(name) return int(value) if value else default TRIALS = env_int("BENCH_N", 20) KEYS = env_int("BENCH_KEYS", 200) def wait_output(fd, secs=5.0): """Read one non-empty chunk of output, or fail.""" end = time.perf_counter() + secs while True: left = end - time.perf_counter() r, _, _ = select.select([fd], [], [], max(left, 0)) if not r: raise SystemExit("editor.py: no output from the shell") try: if os.read(fd, 4096): return except OSError: raise SystemExit("editor.py: the shell exited") from None def one_trial(exe): """Return (seconds to first prompt, seconds per key).""" start = time.perf_counter() pid, fd = pty.fork() if pid == 0: os.environ.update(TERM="vt100", PS1="> ", PS2="> ", ENV="", HOME=os.getcwd()) os.execv(exe, [exe, "-i"]) # noqa: S606 - the shell under test fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0)) wait_output(fd) startup = time.perf_counter() - start for _ in range(10): os.write(fd, b"a") wait_output(fd) keys = [] for _ in range(KEYS): t = time.perf_counter() os.write(fd, b"a") wait_output(fd) keys.append(time.perf_counter() - t) os.write(fd, b"\x15exit\r") with suppress(ChildProcessError): os.waitpid(pid, 0) os.close(fd) return startup, statistics.median(keys) def main(): shells = sys.argv[1:] if not shells: raise SystemExit("usage: bench/editor.py shell [shell ...]") print(f"{'shell':<24} {'start ms':>10} {'key us':>10}") for exe in shells: starts, keys = [], [] for _ in range(TRIALS): s, k = one_trial(exe) starts.append(s) keys.append(k) print(f"{exe:<24} " f"{statistics.median(starts) * 1e3:>10.2f} " f"{statistics.median(keys) * 1e6:>10.1f}") if __name__ == "__main__": main()