Files
fastwc/docs/PERFORMANCE.md
T
huntedbytheirs a2fef6ce5c Say what the multibyte block kernel changed, and where it still loses
The 100 MB numbers replace the 10 MB ones, because 10 MB was measuring
process startup as much as the decoder. Characters in dense CJK now beat
the clone by 2.5x; words and longest line still lose to it by a quarter,
which the divergences section says out loud instead of leaving the reader
to find it. The -c and -m rows join the head-to-head table: no stream is
opened for a count that is a file size.
2026-11-15 13:51:33 -05:00

296 lines
16 KiB
Markdown

# Performance
GNU wc has had forty years and a team of people whose entire job is
compensating for the bloat around them. Here is what they bought with
that time, and what we paid for it.
## The scoreboard, with receipts
Benchmarked on an AMD Ryzen AI 7 PRO 350 — 8 cores / 16 threads, boost
up to 5.09 GHz, 384 KiB L1d / 256 KiB L1i / 8 MiB L2 / 16 MiB L3 —
with 64 GiB of DDR5-4800 dual-channel. Opponents: GNU coreutils 9.11,
busybox 1.36.1, toybox 0.8.13. Page-cache-warm files, min of 3
interleaved runs, both sides timed at microsecond resolution by a C
timer. Only *raced* cases appear below — anything the reference
finishes in under 5 ms is startup, not throughput, and gets reported
but excluded (see "On startup" below). Every number survived contact
with the contract.
| Case | GNU coreutils | busybox | toybox | fastwc |
|------|--------------:|--------:|-------:|-------:|
| words, 1M lines (11 MB) | 7.9ms | 16.2ms | 15.9ms | **1.6ms** |
| words, 10M lines (110 MB) | 66ms | 160ms | 157ms | **5.1ms** |
| lines, 1M (11 MB) | startup | 16.9ms | 17.6ms | **1.6ms** |
| lines, 10M (110 MB) | 5.8ms | 160ms | 154ms | **4.6ms** |
| lines, 100M (monster) | 47.5ms | — | — | **29.2ms** |
| lines, 1B (solo) | — | — | — | **266ms** |
| stdin lines, 10M | 5.9ms | 161ms | 154ms | **4.6ms** |
| stdin words, 1M | 7.1ms | 16.0ms | 16.5ms | **1.5ms** |
| longest line, 110MB | 157ms | — | — | **10.4ms** |
| longest line, 1.1GB | 1506ms | — | — | **61.5ms** |
| 1050 files of 1MiB, `-lwc` | 1509ms | — | — | **45ms** |
That is a 13x win over GNU on 10M lines of words, 4.9x on 1M, and 1.6x
on the 100M monster. `-L` used to be the exception — a serial walk that
lost to GNU on anything past a few megabytes. It is now the biggest win
in the table: 15x at 110 MB, 24x at 1.1 GB, and 2.3x faster than the
Rust clone that used to own the case. GNU's threaded counter manages a
genuine dead heat at 110 MB of plain lines (5.8ms vs our 4.6ms — it never
wins; we allow it a 2% tie margin and it still can't take it). The moment
the file stops fitting in a polite buffer, the dead heat stops being
polite. At 1B lines — 11 GB, which this machine's 64 GiB actually
fits — the solo run lands at 266ms: 41.4 GB/s, 3.76 billion lines per
second. The reference is us now. Busybox and toybox, meanwhile, are
here for the cruelty: 10-31x slower depending on the case, and their
word counting has *bugs*.
## The locale tax, gone
Every number above is C locale — the setting that flatters the
opponents most: GNU `wc -w` under a UTF-8 locale stops counting bytes
and decodes every one of them through `mbrtowc`, even when the file is
pure ASCII and decoding changes nothing. We used to pay that same tax:
the multibyte gate looked only at `MB_CUR_MAX`, so a UTF-8 locale
silently traded the SIMD kernels for the decoder, and the 11 MB words
race above flipped from a 4.9x win to a 25% loss against GNU.
The kernels now double as a probe — one vector move-mask per load
flags the first byte ≥ 0x80, free when unused — so only files that
actually contain a high byte fall back to the decoder. Receipts,
min-of-N interleaved, `en_US.UTF-8`, the same 11 MB ASCII words file:
| Case | GNU coreutils | fastwc | gap |
|------|--------------:|-------:|----:|
| words | 10.43ms | **1.38ms** | 7.6x |
| default (`-lwc`) | 10.55ms | **1.50ms** | 7.0x |
| characters (`-m`) | 10.58ms | **2.06ms** | 5.1x |
| longest line (`-L`) | 10.56ms | **6.83ms** | 1.5x |
GNU's decoder bill for that file is unchanged: 10.4ms, for bytes that
were never multibyte. Files that genuinely are multibyte still decode
at parity — 10.5 MB of mixed CJK+latin, 56.7ms against GNU's 56.9ms —
because there both sides decode. The one case GNU keeps is *lightly*
multibyte files: sparse UTF-8 costs us one wasted fast pass before the
fallback (793 KB, 1.30ms vs GNU's 1.18ms). We judged the tax worth
it; ASCII is the rule, multibyte is the exception.
## On startup
A word counter that loses one-line races to a slower counter is not
slower — it's slower to *start*, and the benchmark used to punish that
with integer-millisecond `date`-fork rounding. We fixed the honest
half and then the honest reporting:
- **What startup used to cost.** Staged-exit probes with a min-of-N
exec timer showed ~105µs of avoidable work above the glibc exec
floor: `setlocale` (~44µs), a `nl_langinfo` quote-style probe used
only by one error message (~26µs), two 256-entry `isspace`/`isprint`
table fills (~39µs), and runtime CPU dispatch — all of it paid even
for `--help` and `-c`.
- **What we did about it.** The locale chain (`LC_ALL` → `LC_CTYPE` →
`LANG`) is resolved first and `setlocale` is skipped entirely when it
resolves to C/POSIX or is unset — glibc's initial locale *is* C, so
the semantics are identical. The quote-style probe went lazy (only
the `--total=` error diagnostics ever print curly quotes). The
whitespace/print tables are constant-filled under the C locale and
built only when the flags need them (`-w`, `-L`). Option parsing
moved ahead of everything, so `--help`, `--version`, and usage
errors exit with zero startup cost.
- **The receipts.** Min-of-400 interleaved on an 11-byte file: fastwc
~0.25ms, GNU ~0.33ms, toybox ~0.37ms, busybox ~0.14ms. Before the
work, fastwc `-w` on a tiny file measured ~562µs; after, ~425µs.
Nobody will ever notice a difference that small. Those were the
dynamic-link numbers; the static musl default below starts ~3x
sooner than even those.
- **The honest half.** Because those microseconds don't matter, the
benchmark no longer pretends they do. Any case the reference
finishes in under 5ms is filed under `startup-bound`: fastwc must
still match the count, but the case is excluded from the averages
and the throughput scoreboard. Busybox used to win these outright —
it is a static musl binary, and skipping the dynamic loader bought
it the better part of a hundred microseconds on every exec. That
excuse retired itself when the default build went static musl too
(see the README): on a 12-byte file, min-of-400, fastwc `-l` now
lands at 78µs against busybox's 83µs, GNU's 253µs, and toybox's
254µs. The cases in the table above are the ones where counting
takes longer than starting.
## Why it's fast
1. **SIMD kernels, dispatched at runtime.** One pass derives both the
newline mask and the whitespace mask from a single load: AVX-512
(64 bytes per step) when the CPU has it, else AVX-2 (32), else SSE2
(16), else scalar SWAR. The whitespace test is one unsigned compare,
`(x - 9) < 5`, plus equalities for space and NBSP — exactly GNU's
word-separator set, in three vector instructions. Dispatch itself is
lazy: the CPUID probe runs only when a count will actually use it.
2. **Regular files are mapped, not streamed.** `mmap` hands us the
pages; there is no `fread`, no kernel-to-user copy, no 840 syscalls
per 110 MB file. One syscall in, one count out. A stdin redirect
from a regular file (`fastwc -l < file`) gets the same treatment —
the data comes through stdin, but how we read it is our business.
The stdin suite is why this shows up in the scoreboard too.
3. **Parallel across cores, sized to the work.** A thread has to earn its
spawn, which costs about what counting 512 KiB costs, so a mapping
gets one slice per 512 KiB (256 KiB for `-L`, whose kernel is several
times the work per byte), capped at the CPUs the process may actually
use. That number comes from `sched_getaffinity`, narrowed by the
cgroup CPU quota when one is set, with `sysconf` as the last resort —
`sysconf` answers for the whole machine, which is the wrong answer
under `taskset` and the wrong answer inside a container. The kernels
are pure, so the split needs no locks; word boundaries between slices
are seeded from the byte before the slice, which makes the split
exact.
4. **A long file list runs on a pool.** Past eight names, one worker per
core takes the next file and the rows are printed in argument order
when they finish. A thousand 1 MiB files spend nearly all their time
in the kernel, so the pool is the difference between 45 ms and 150 ms.
The workers turn off per-file slicing: two layers of parallelism only
oversubscribe each other.
5. **`-L` folds by maximum.** A line's width depends on where the line
starts, which looks like sequential state. It isn't: a slice that
begins at a line end needs nothing from its neighbours, and the fold
is a max. Inside a block, the printable lanes are prefix-summed, the
values at the line ends are packed together with one compress, and one
subtract turns them into every line width the block ends. Two or
sixty lines per block cost the same. Blocks with a tab walk their runs
instead, because a tab stop depends on where in the line it sits.
6. **No work that isn't asked for.** `-c` on a regular file is `st_size`
from `fstat` — GNU figured that one out too, so we copied the good
idea, and extended it to `-m` in a single-byte locale, where a
character is a byte. Then we stopped opening a stream for it at all:
the size the column width was computed from is the answer, so a
thousand small files cost the stat pass and a row each. `-l` without
`-w` skips the whitespace mask entirely; `-w` without `-L` never
builds the print table.
7. **ASCII pays nothing, even in a UTF-8 locale.** Multibyte decoding is
expensive, so we don't volunteer for it. A sample of the first few
KiB and two points in the middle decides whether a file is worth
decoding at all, which saves the wasted probe pass on files that are
multibyte everywhere. Files the sample calls ASCII still run the SIMD
probe, so a late high byte costs one wasted pass and nothing else.
When a file really is UTF-8, the mapping is split into chunks that
start at line ends and decode independently (UTF-8 has no shift
state), ASCII stretches inside each chunk go to the byte kernels, and
only the characters around a high byte are decoded one at a time.
Malformed bytes fall back to the streaming decoder, whose error
handling is GNU's, byte for byte.
## The `-L` hole, closed
`-L` was the one thing this program was bad at: a serial walk of the
mapped file at 0.7 GB/s. Against the Rust clone it lost 6-8x, and it lost
to GNU on the big files. Three kernels later it doesn't:
| case | before | after | Rust clone | GNU |
|------|-------:|------:|-----------:|----:|
| `-L`, 11 MB | 13.2 ms | **1.9 ms** | 4.3 ms | 16.6 ms |
| `-L`, 110 MB | 136 ms | **10.4 ms** | 21.4 ms | 157 ms |
| `-L`, 1.1 GB | 1204 ms | **61.5 ms** | 142 ms | 1506 ms |
| `-L`, 11 GB | 11.9 s | **0.56 s** | 1.29 s | 15.3 s |
The kernel ladder: scalar for anything the CPU can't do better,
AVX-2 (32-byte masks, run walk), AVX-512 (64-byte masks, same walk), and
AVX-512 with VBMI2 (prefix-summed printable lanes, compressed line-end
values, one packed subtract). Measured on one core over 110 MB of
11-byte lines: 0.67 GB/s scalar, 1.27 AVX-2, 1.55 AVX-512, 3.39 for the
prefix-sum walk. The last one is not a wider vector; it's less work per
line.
## The multibyte path, split
The UTF-8 decoder used to be the same story: correct, GNU-exact, and
serial. It paid for every byte of a file, after a probe pass had already
read the whole thing once. Now a UTF-8 file is split at line ends, each
chunk decodes without inheriting state, ASCII stretches go to the byte
kernels, and dense CJK is counted a 64-byte block at a time from masks:
characters as bytes minus continuations, lines from the newline mask,
words from a byte-level white-space mask. A block that is not exactly
ASCII plus three-byte characters is refused and decoded the slow way, so
the fast path never guesses. 100 MB under `en_US.UTF-8`:
| case | before | after | Rust clone | GNU |
|------|-------:|------:|-----------:|----:|
| words, lightly multibyte | 6.8 ms | **5.5 ms** | 6.2 ms | 224 ms |
| longest line, lightly multibyte | 26.2 ms | **9.1 ms** | 11.6 ms | 223 ms |
| characters, dense CJK | 46.2 ms | **7.6 ms** | 18.7 ms | 458 ms |
| words, dense CJK | 55.8 ms | **8.6 ms** | 6.8 ms | 464 ms |
| longest line, dense CJK | 59.1 ms | **43.1 ms** | 33.7 ms | 587 ms |
The clone still wins words and longest line on dense CJK, by 26% and
28%, because it carries its own width table and trusts the encoding where
we validate and call `wcwidth`. Both of us are 20 to 50 times ahead of
GNU there, and on everything else - ASCII, lightly multibyte text,
characters in any mix - we are ahead of the clone. This is the honest
state of the one case it still owns.
## Threads you actually have
`sysconf(_SC_NPROCESSORS_ONLN)` reports the machine. A process under
`taskset -c 0-3` has four CPUs, a container with `cpu.max = 200000
100000` has two, and a 128-core server whose cgroup gives you eight has
eight. Oversubscribing a quota buys wall-clock noise, not throughput.
`cpu_count()` takes the affinity mask, narrows it by the cgroup v2 quota
(or the v1 pair), and only falls back to `sysconf` when neither answers.
It runs lazily, on the first mapping big enough to be sliced, so tiny
files never pay for it.
## Correctness is the other half of the contract
The benchmark compares counts, not just clocks — against all three
oracles. Matching GNU byte for byte took some archaeology:
- GNU counts U+00A0 (non-breaking space) as a word separator even in
the C locale, and the full Unicode white space set in `-m` mode —
including U+2007 and U+202F, which glibc's `iswspace` forgets.
- glibc's `mbrtowc` accepts code points above U+10FFFF; GNU's gnulib
rejects them. So do we.
- In a single-byte locale, GNU's `-m` counts bytes, not characters.
So do we now.
- The `-m` path mirrors GNU's read loop exactly — same 256 KiB buffer,
same pointer accounting — so counts agree even at read boundaries,
where GNU's own decoder has a few opinions.
The selftest (`cc -DFASTWC_SELFTEST src/main.c`) checks every kernel
against the scalar reference over all sizes, both carry states, and
both counting modes, plus the threaded slice split. Every width kernel
is checked the same way, from a line start and from a carried line
position, and the split width pass is checked against one serial pass for
every thread count. A randomized fuzz against GNU as oracle (both
locales, binary and UTF-8 data, every flag combination) passes 100%.
## Known divergences, stated plainly
- **Dense CJK still belongs to them on two flags.** `-w` and `-L` over
text that is multibyte end to end are 26% and 28% behind the Rust
clone, which carries its own width table and does not validate the
encoding. We validate every block and call `wcwidth`, because the
counts have to match GNU on every code point, and both of us are 20 to
50 times ahead of GNU there. Characters (`-m`) and every ASCII or
lightly multibyte case are ours.
- **A tab-heavy block walks its runs.** The prefix-sum width kernel
assumes a printable byte is worth one column. A tab is worth between
one and eight depending on where in the line it sits, so any block
containing one falls back to the per-run walk: still vectorized, about
half the speed of the prefix-sum path. Text without tabs is the norm.
- **GNU wc's count is transport-dependent.** The same bytes piped into
`wc -mw` can count differently than the same bytes read from a file,
because 64 KiB pipe chunks trigger a re-scan of its carried bytes.
We reproduced this, then declined to. fastwc counts the data, not
the plumbing.
## Reproducing
```sh
make bench # build release + run every suite
./benchmarks/test-all.sh # words, lines (monsters included), stdin
```
`test-all.sh` compiles its two helper tools on the spot
(`tools/genfile` for the test data, `tools/timeit` for microsecond
timing) — no separate setup. The suites live in
`benchmarks/files/{lines,words}` and `benchmarks/stdin/piping`, and
race all three oracles in one run. The lines suite ends with the
monsters: 100M lines raced against coreutils, and 1B lines timed solo
(no reference to beat — the reference is us now).