summaryrefslogtreecommitdiffhomepage
path: root/bench/editor.py
blob: e6d324084486341b4f702f7e4638e23b1815ece5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/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()