Compare commits

..
8 Commits
Author SHA1 Message Date
huntedbytheirs c45de29b0c Race the UTF-8 decoder against coreutils
Every case in the suite pinned LC_ALL=C, so the multibyte path - the one
whose counts go wrong quietly rather than crashing - had no contract
behind it at all. genfile grew a --utf8 mode that writes mixed CJK,
ASCII words, a tab, an ideographic space, a no-break space and a
combining accent, and the words suite now races -w, -m and -L over 300k
lines of it under en_US.UTF-8 (C.UTF-8 as a fallback), against coreutils.

The case runs the locale on both sides rather than inheriting the C pin,
because the oracle's own decoder is the reference. It prints SKIP rather
than passing when the host has no UTF-8 locale: a multibyte count cannot
be checked in a single-byte one.
2026-11-15 14:00:07 -05:00
huntedbytheirs 9b68ad4c6c Race -L and the file list in the benchmark suite
The numbers for -L and for a long file list lived in a scratch harness,
so nothing in the repository would fail if either regressed. The lines
suite now races -L at 1M and 10M lines against every oracle, and ends
with 128 files holding 12.8M lines counted in one invocation, which is
where the worker pool lives.

The file-list check compares the row count and the total row's numbers
rather than the whole output: busybox and toybox pad their columns
differently, and an exact string compare would fail on their formatting
instead of on our arithmetic.
2026-11-15 13:58:13 -05:00
huntedbytheirs 47188fbef1 Record the -L probe fix in the multibyte table
ASCII under a UTF-8 locale was reading the file twice for one number;
it now sits at 9.5 ms, a shade ahead of the Rust clone and the same as
the C locale. The lightly multibyte row is quoted as a range because two
runs a minute apart disagree by 13%.
2026-11-15 13:56:11 -05:00
huntedbytheirs aa1fc2a42e Let the width pass probe for high bytes instead of a second read
-L alone under a UTF-8 locale ran the lines/words kernel as a high-byte
probe, then the width pass: two reads of the whole file for one number,
and the probe produced nothing because there were no lines or words to
count. The width kernels now take the probe themselves - one move-mask
per block, already computed for the printable mask in the AVX-512 walk -
and count_mapped skips the byte pass when -L is the only count asked for.

100 MB of ASCII under en_US.UTF-8: 21.7 ms to 9.5 ms, against the Rust
clone's 10.2 and the 10.5 the same file takes in the C locale. A file
whose only high byte sits past the sample still trips the probe, and the
chunked pass still hands the whole file to the streaming decoder.
2026-11-15 13:56:03 -05:00
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
huntedbytheirs 3194a21aec Count dense CJK from masks, and bytes without opening a stream
Dense CJK was the last place the Rust clone beat us: every character
was decoded one at a time, in a loop whose branches always went the same
way. A 64-byte block of ASCII and three-byte characters is now counted
from masks instead - characters as bytes minus continuations, lines from
the newline mask, words from a byte-level white-space mask in which
every byte of a white-space character is marked, so a byte transition is
a character transition. A block is only accepted when it validates as
exactly that shape (continuations one and two bytes after their lead, no
overlong, no surrogate, no character running off either end), and a
refused block falls back to the character loop.

100 MB of CJK under en_US.UTF-8: characters 46.2 ms to 7.6 ms (the
clone's 18.7), words 55.8 ms to 8.6 ms (the clone's 6.8), longest line
59.1 ms to 43.1 ms. Lightly multibyte text is at or ahead of the clone
on every flag.

Also: -c and single-byte -m answer from the size the column width was
computed from, so a thousand small files cost the stat pass and nothing
else. 1050 x 1 MiB: -c 4.4 ms to 2.1 ms (the clone's 3.7), -m 2.7 ms
against the clone's 30.8.

Two fixes found on the way: the multibyte fallback restored its counts
after a chunked pass bailed and then decoded on top of the partial
sums, and the SIMD width kernels were disabled outside the C locale even
though a UTF-8 locale prints exactly the same ASCII.
2026-11-15 13:51:07 -05:00
huntedbytheirs 35d121e6ea Charge the scoreboard for -L and the other fastwc
-L is now the widest gap in the table rather than the one case we lost,
so the README stops pretending that "never slower" covered it and says
where the numbers came from. The Rust clone that held the record gets
its own section: what it did right, what it still wins (dense CJK, by
carrying a width table where we call wcwidth), and what it lost.

PERFORMANCE.md gets the receipts: the -L kernel ladder with one-core
throughput per kernel, the UTF-8 numbers before and after the split
decode, the thread-count rules, and the tab and CJK cases stated as
divergences instead of hidden.
2026-11-15 13:38:32 -05:00
huntedbytheirs 5d2aee2f1d Speed up -L, multibyte decoding, and long file lists
-L was a serial byte-at-a-time walk, the multibyte path decoded every
byte of a file serially after wasting a probe pass on it, and a long
file list was counted one file at a time.

- Width now has its own kernel family: scalar, AVX-2, AVX-512, and an
  AVX-512+VBMI2 prefix-sum walk that computes a whole block's line
  widths at once. Slices start after a line end, so they fold by
  maximum and -L runs across cores.
- UTF-8 chunks decode independently (no shift state), ASCII stretches
  go to the byte kernels, and only the characters around a high byte
  are decoded. A first-KiB sample skips the wasted probe pass, and
  malformed input falls back to the streaming decoder's GNU-exact
  error handling.
- Thread count follows a cost model (a thread per half megabyte, a
  quarter for -L) over sched_getaffinity narrowed by the cgroup CPU
  quota instead of a machine-wide sysconf count.
- File lists of eight or more are counted on a worker pool, one file
  per worker, with rows printed in argument order and errors serialized.
- -m in a single-byte locale uses the file size like -c already did.

1060 MB of 1050 files: 45 ms against GNU's 1.5 s and the Rust clone's
145 ms. -L on 1.1 GB: 62 ms against 1.5 s and 142 ms.
2026-11-15 13:36:47 -05:00
7 changed files with 2193 additions and 152 deletions
+83 -4
View File
@@ -35,6 +35,9 @@ laptop APU, which is where the rest of you live:
| lines, 1B solo | **266 ms.** 11 GB in one pass at 41.4 GB/s — 3.76 billion lines per second. We are the reference now. | | lines, 1B solo | **266 ms.** 11 GB in one pass at 41.4 GB/s — 3.76 billion lines per second. We are the reference now. |
| stdin lines, 10M | **4.6 ms vs coreutils 5.9 ms (1.28x).** Busybox 16.6x (161 ms), toybox 16.8x (154 ms). | | stdin lines, 10M | **4.6 ms vs coreutils 5.9 ms (1.28x).** Busybox 16.6x (161 ms), toybox 16.8x (154 ms). |
| stdin words, 1M | **1.5 ms vs coreutils 7.1 ms (4.7x).** GNU reads stdin like it's 1985. Busybox 12.7x, toybox 10.4x. | | stdin words, 1M | **1.5 ms vs coreutils 7.1 ms (4.7x).** GNU reads stdin like it's 1985. Busybox 12.7x, toybox 10.4x. |
| longest line, 110 MB | **10.4 ms vs coreutils 157 ms (15.1x).** Busybox 23.9x, toybox 21.0x. `-L` used to be our *worst* case. It isn't any more. |
| longest line, 1.1 GB | **61.5 ms vs coreutils 1.51 s (24.5x).** Busybox and toybox are not invited to this one. |
| 1050 files of 1 MiB, `-lwc` | **45 ms vs coreutils 1.51 s (33.5x).** A thousand small files is a scheduling problem, not a counting problem. |
Measured on an AMD Ryzen AI 7 PRO 350 — 8 cores / 16 threads, boost up Measured 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 to 5.09 GHz, 384 KiB L1d / 256 KiB L1i / 8 MiB L2 / 16 MiB L3 — with
@@ -93,7 +96,7 @@ excluded from the averages — because nobody should be racing startup,
least of all a word counter. The cases that matter are the ones where least of all a word counter. The cases that matter are the ones where
counting takes longer than starting — and those are the ones in this counting takes longer than starting — and those are the ones in this
table. Every run ends with the average speedup against each oracle — table. Every run ends with the average speedup against each oracle —
coreutils ~4.5x, busybox ~13-15x, toybox ~15-18x — so the cruelty is coreutils ~8-9x, busybox ~37-47x, toybox ~32-36x — so the cruelty is
quantified. quantified.
## Why ## Why
@@ -108,6 +111,17 @@ quantified.
now: regular files are mapped and counted in parallel across cores, now: regular files are mapped and counted in parallel across cores,
with SIMD kernels (AVX-512, AVX-2, SSE2) dispatched at runtime — with SIMD kernels (AVX-512, AVX-2, SSE2) dispatched at runtime —
zero function calls in the hot path. zero function calls in the hot path.
- **`-L` is not an afterthought.** The longest-line pass used to be the
one thing this program was bad at, because a line's width depends on
where it starts, which looks sequential. It isn't: a slice that begins
at a line end folds by maximum. Sixty-four bytes at a time, the
printable lanes are prefix-summed and the values at the line ends are
packed together, so one subtract yields every line width in the block.
24x faster than GNU on 1.1 GB, and 2.3x faster than the Rust clone
that used to beat us at it.
- **A long file list is a scheduling problem.** Past eight files the list
runs on a worker pool, one file per worker, rows still in argument
order. A thousand megabyte files take 45 ms; GNU takes 1.5 s.
- **GNU wc slows down in the locale you actually run.** Under a UTF-8 - **GNU wc slows down in the locale you actually run.** Under a UTF-8
locale it decodes every byte it counts — pure ASCII included, which locale it decodes every byte it counts — pure ASCII included, which
decoding cannot change — so the 11 MB words file that takes it decoding cannot change — so the 11 MB words file that takes it
@@ -115,6 +129,67 @@ quantified.
fastwc's kernels probe for non-ASCII bytes as they count and only fastwc's kernels probe for non-ASCII bytes as they count and only
decode files that need it. The locale that taxes GNU is free for us. decode files that need it. The locale that taxes GNU is free for us.
## The other fastwc
There is another project called fastwc. It is written in Rust, which it
mentions. Every build of it compiles a tree of crates with a progress
bar, the way Rust does, and the result is a word counter that was, for a
few months, faster than ours at `-L`.
It posted 22x, and it had earned it. We were walking the file one byte at
a time, in one thread, while it split the mapping at newlines and ran an
AVX-2 width kernel per chunk. Good idea, honestly. So we took it, and
then took it further, because an old dog can learn new tricks and then
bite with them.
| case | that fastwc | this fastwc |
|------|------------:|------------:|
| `-L`, 110 MB | 21.4 ms | **10.4 ms** |
| `-L`, 1.1 GB | 142 ms | **61.5 ms** |
| `-L`, 11 GB | 1.29 s | **0.56 s** |
| 1050 × 1 MiB, `-lwc` | 145 ms | **45 ms** |
| 1050 × 1 MiB, `-L` | 1.23 s | **66 ms** |
| 1050 × 1 MiB, `-c` | 3.7 ms | **2.1 ms** |
| 1050 × 1 MiB, `-m` | 30.8 ms | **2.7 ms** |
Same files, same machine, both binaries racing the clock back to back.
Read the `-L` row twice: on a thousand small files we are eighteen times
faster at the one thing it used to win, because the width kernel now
computes a whole 64-byte block's line widths with prefix sums and one
packed subtract, and a long file list is spread over the cores instead of
counted one file at a time. The `-c` and `-m` rows are the other half of
that: a count that is a file size never opens the file.
Rust is the femboy language of systems programming: spotless hygiene,
elaborate safety equipment, and a firm opinion about how you should be
holding its hand. Memory safety is a fine goal for people who cannot
remember a few extra facts about a language. The rest of us have
`-Wall -Wextra`, a benchmark that fails on a single miscounted word, and
a self-test that runs every kernel against a scalar reference — which has
caught more real bugs in this one file than a borrow checker ever caught
in a program whose job is to read a file and add up three numbers. We'll
keep the pointers.
To be fair to their code: the `par_iter` over newline chunks is the right
shape, and their AVX-2 segment walk is clever. Rust isn't why they are
slower. Arithmetic is. A 32-byte AVX-2 block gives you one mask per
instruction; a 64-byte block with a prefix sum gives you every line width
in the block for one subtract, and after that the block costs the same
whether it holds one line or sixty. That isn't a language feature. It's
maths their kernel doesn't do, and ours does.
The same goes for the locale. Their "decode only around the high bytes"
instinct was right, so the UTF-8 path splits the mapping into chunks that
decode independently, hands every ASCII stretch to the byte kernels, and
counts dense CJK a 64-byte block at a time from masks rather than a
character at a time. 100 MB of lightly thé'd text under `en_US.UTF-8`:
**5.5 ms**, against their 6.2 and GNU's 224. On dense CJK characters we
are 7.6 ms against their 18.7; on CJK words and longest line they still
have us by a quarter, because they keep a width table and trust the
encoding where we validate and call `wcwidth` to match GNU exactly. We
will take a quarter of a loss on two flags of one alphabet for exact
counts on all of them.
## What it does ## What it does
``` ```
@@ -182,9 +257,13 @@ cases allow a 2% dead-heat margin so a genuine tie can't flake — but a
real loss writes a shame report, fails the suite, and exits non-zero. real loss writes a shame report, fails the suite, and exits non-zero.
The words suite grows to 1M and 10M lines; the lines suite carries the The words suite grows to 1M and 10M lines; the lines suite carries the
monsters: 100M lines raced against coreutils, and 1B lines timed solo monsters: 100M lines raced against coreutils, and 1B lines timed solo
— there is no reference for that one; we are the reference now. When — there is no reference for that one; we are the reference now. The
the run ends, the average speedup of fastwc against each oracle is lines suite also races `-L` at 1M and 10M lines, and ends with a
printed. 128-file list (12.8M lines) so the worker pool is under the contract
too, not just in some table in this file. The words suite finishes with
`-w`, `-m` and `-L` over mixed UTF-8 text under a real UTF-8 locale,
because the decoder's counts are the ones that go wrong quietly. When the run ends, the
average speedup of fastwc against each oracle is printed.
## Development ## Development
+14
View File
@@ -30,6 +30,12 @@ for oracle in $ORACLES; do
exit 1 exit 1
fi fi
printf '\n%s\n' '--- longest line ---'
if ! run_cases lines -L 1000000 10000000; then
exit 1
fi
printf '\nall %s lines benchmarks passed — fastwc was never slower than %s wc\n' \ printf '\nall %s lines benchmarks passed — fastwc was never slower than %s wc\n' \
"$BENCH_NAME" "$BENCH_NAME" "$BENCH_NAME" "$BENCH_NAME"
done done
@@ -45,3 +51,11 @@ fi
printf '%s\n' '--- monster: 1B lines, solo ---' printf '%s\n' '--- monster: 1B lines, solo ---'
run_solo_case 1000000000 -l run_solo_case 1000000000 -l
# A file list is where the worker pool lives, and it needs files big
# enough that both sides are counting rather than starting. 128 files of
# about 1.1 MB, 140 MB in total.
printf '%s\n' '--- file list: 128 files, 12.8M lines, vs coreutils ---'
if ! run_multi_case lines 128 12800000 -lwc; then
exit 1
fi
+16
View File
@@ -30,3 +30,19 @@ for oracle in $ORACLES; do
printf '\nall %s words benchmarks passed — fastwc was never slower than %s wc\n' \ printf '\nall %s words benchmarks passed — fastwc was never slower than %s wc\n' \
"$BENCH_NAME" "$BENCH_NAME" "$BENCH_NAME" "$BENCH_NAME"
done done
# The multibyte path, raced against coreutils only: under a UTF-8 locale
# wc decodes, and the case is about our decoder agreeing with its counts
# and beating its speed. 300k mixed lines is about 6 MB, which is enough
# for both sides to be counting rather than starting.
select_oracle coreutils || exit 1
printf '\n%s\n' '--- multibyte, UTF-8 locale (coreutils) ---'
if ! run_utf8_case words 300000 -w; then
exit 1
fi
if ! run_utf8_case chars 300000 -m; then
exit 1
fi
if ! run_utf8_case 'longest line' 300000 -L; then
exit 1
fi
+114
View File
@@ -33,6 +33,17 @@ set -u
export LC_ALL=C export LC_ALL=C
export LC_CTYPE=C export LC_CTYPE=C
# One UTF-8 locale for the multibyte cases, or empty when the host has
# none: those cases need real decoding on both sides, so they run under
# it explicitly rather than inheriting the C locale above.
UTF8_LOCALE=''
for cand in en_US.UTF-8 C.UTF-8; do
if LC_ALL="$cand" locale charmap 2>/dev/null | grep -qi 'utf-8'; then
UTF8_LOCALE="$cand"
break
fi
done
FASTWC="$REPO_DIR/bin/release/fastwc" FASTWC="$REPO_DIR/bin/release/fastwc"
DATA_DIR="$SCRIPT_DIR/.data" DATA_DIR="$SCRIPT_DIR/.data"
GENFILE="$REPO_DIR/benchmarks/tools/genfile" # optional C helper, built by test-all.sh GENFILE="$REPO_DIR/benchmarks/tools/genfile" # optional C helper, built by test-all.sh
@@ -403,6 +414,109 @@ run_cases() {
return $rc return $rc
} }
# run_multi_case <mode> <files> <lines total> <flag> — race a list of files.
# A list is where the worker pool lives: one file per worker, rows printed
# in argument order. Correctness is the whole output, not one column,
# because a pool that reorders or drops a row would still total up.
run_multi_case() {
local mode="$1" nfiles="$2" lines="$3" flag="$4"
local label="$mode (${nfiles} files, ${lines} lines)"
local src dir name i d wc_out fast_out wc_us fast_us
local -a files=()
src=$(createtxt "$lines") || return 1
dir="$DATA_DIR/multi-${nfiles}-${lines}"
if [[ ! -f "$dir/.ready" ]]; then
rm -rf "$dir"
mkdir -p "$dir"
split -n "$nfiles" -d -a 3 "$src" "$dir/part-" || return 1
: > "$dir/.ready"
fi
for name in "$dir"/part-*; do
files+=("$name")
done
# The oracles pad their columns differently, so the check is the row
# count (nothing dropped or reordered) and the total row's numbers.
wc_out=$("${WC_CMD[@]}" "$flag" "${files[@]}" 2>/dev/null |
awk 'END { print NR ":" $1, $2, $3 }')
fast_out=$("$FASTWC" "$flag" "${files[@]}" 2>/dev/null |
awk 'END { print NR ":" $1, $2, $3 }')
wc_us=''
fast_us=''
for ((i = 0; i < BENCH_REPS; i++)); do
d=$(timeit "${WC_CMD[@]}" "$flag" "${files[@]}")
[[ -z "$wc_us" || "$d" -lt "$wc_us" ]] && wc_us="$d"
d=$(timeit "$FASTWC" "$flag" "${files[@]}")
[[ -z "$fast_us" || "$d" -lt "$fast_us" ]] && fast_us="$d"
done
finish_race "$label" "$wc_out" "$fast_out" "$wc_us" "$fast_us"
}
# createtxt_utf8 <lines> — mixed UTF-8 text (CJK, words, spaces, a
# combining accent) in this suite's .data directory. Prints the path and
# sets $TEXT_FILE; the file is reused when its name matches.
createtxt_utf8() {
local lines="$1"
TEXT_FILE="$DATA_DIR/utf8-$lines.txt"
if [[ ! -s "$TEXT_FILE" ]]; then
mkdir -p "$DATA_DIR"
if [[ -x "$GENFILE" ]]; then
"$GENFILE" --utf8 "$lines" > "$TEXT_FILE" || {
printf 'createtxt_utf8: error: failed to generate %s\n' \
"$TEXT_FILE" >&2
return 1
}
else
printf 'createtxt_utf8: error: %s not built\n' "$GENFILE" >&2
return 1
fi
fi
printf '%s\n' "$TEXT_FILE"
}
# run_utf8_case <mode> <lines> <flag> — race under a UTF-8 locale, where
# -w/-m/-L go through the decoder instead of the byte kernels. The
# oracle's own multibyte semantics are the reference here, which is why
# the case has to run in the locale rather than pinned to C.
run_utf8_case() {
local mode="$1" lines="$2" flag="$3"
local label="$mode utf8 (${lines} lines)"
local file wc_count fast_count wc_us fast_us i d
if [[ -z "$UTF8_LOCALE" ]]; then
printf '%-28s %16s %24s %8s %s\n' "$label" '-' '-' '-' \
'SKIP (no UTF-8 locale)'
return 0
fi
file=$(createtxt_utf8 "$lines") || return 1
wc_count=$(capture_count env LC_ALL="$UTF8_LOCALE" LC_CTYPE="$UTF8_LOCALE" \
"${WC_CMD[@]}" "$flag" "$file")
fast_count=$(capture_count env LC_ALL="$UTF8_LOCALE" \
LC_CTYPE="$UTF8_LOCALE" "$FASTWC" "$flag" "$file")
wc_us=''
fast_us=''
for ((i = 0; i < BENCH_REPS; i++)); do
d=$(timeit env LC_ALL="$UTF8_LOCALE" LC_CTYPE="$UTF8_LOCALE" \
"${WC_CMD[@]}" "$flag" "$file")
[[ -z "$wc_us" || "$d" -lt "$wc_us" ]] && wc_us="$d"
d=$(timeit env LC_ALL="$UTF8_LOCALE" LC_CTYPE="$UTF8_LOCALE" \
"$FASTWC" "$flag" "$file")
[[ -z "$fast_us" || "$d" -lt "$fast_us" ]] && fast_us="$d"
done
finish_race "$label" "$wc_count" "$fast_count" "$wc_us" "$fast_us"
}
# run_stdin_cases <words|lines> <-w|-l|...> <size...> — run run_stdin_case # run_stdin_cases <words|lines> <-w|-l|...> <size...> — run run_stdin_case
# for every size, stopping at the first failure. # for every size, stopping at the first failure.
run_stdin_cases() { run_stdin_cases() {
+64 -2
View File
@@ -4,9 +4,15 @@
* (createtxt in std.sh) to build test data quickly; std.sh falls back to a * (createtxt in std.sh) to build test data quickly; std.sh falls back to a
* slow shell loop when this binary has not been built. * slow shell loop when this binary has not been built.
* *
* With --utf8 the lines are mixed text instead: CJK runs, ASCII words, a
* tab, and the Unicode spaces, which is the data the multibyte path was
* built for.
*
* usage: genfile <lines> * usage: genfile <lines>
* genfile --utf8 <lines>
*/ */
#include <stdint.h> #include <stdint.h>
#include <string.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
@@ -23,6 +29,18 @@ static const char alpha[] =
static uint64_t state; static uint64_t state;
/* One three-byte code point, U+4E00..U+9FFF, which is where dense CJK
* lives and what the block kernel is written for. */
static size_t emit_cjk(char *out, unsigned r)
{
unsigned cp = 0x4e00 + r % 0x5200;
out[0] = (char)(0xe0 | (cp >> 12));
out[1] = (char)(0x80 | ((cp >> 6) & 0x3f));
out[2] = (char)(0x80 | (cp & 0x3f));
return 3;
}
static uint64_t next(void) static uint64_t next(void)
{ {
state ^= state << 13; state ^= state << 13;
@@ -39,8 +57,15 @@ int main(int argc, char **argv)
char buf[CHUNK]; char buf[CHUNK];
size_t used = 0; size_t used = 0;
int utf8 = 0;
if (argc == 3 && strcmp(argv[1], "--utf8") == 0) {
utf8 = 1;
argv++;
argc--;
}
if (argc != 2) { if (argc != 2) {
fprintf(stderr, "usage: %s <lines>\n", argv[0]); fprintf(stderr, "usage: %s [--utf8] <lines>\n", argv[0]);
return 2; return 2;
} }
n = atol(argv[1]); n = atol(argv[1]);
@@ -53,10 +78,47 @@ int main(int argc, char **argv)
state = (uint64_t)time(NULL) ^ ((uint64_t)getpid() << 32) ^ 0x9E3779B97F4A7C15ULL; state = (uint64_t)time(NULL) ^ ((uint64_t)getpid() << 32) ^ 0x9E3779B97F4A7C15ULL;
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
if (!utf8) {
for (j = 0; j < LINE_LEN; j++) for (j = 0; j < LINE_LEN; j++)
buf[used++] = alpha[next() % ALPHA_LEN]; buf[used++] = alpha[next() % ALPHA_LEN];
} else {
unsigned pick = (unsigned)(next() % 100);
unsigned k, runs;
if (pick < 8) { /* a tab indented line */
buf[used++] = '\t';
}
if (pick < 55) { /* a run of CJK, the dense case */
runs = 1 + (unsigned)(next() % 12);
for (k = 0; k < runs; k++)
used += emit_cjk(buf + used, (unsigned)next());
if (pick < 15) /* ... followed by an ASCII word */
for (j = 0, k = 3 + (unsigned)(next() % 6); j < (int)k; j++)
buf[used++] = alpha[next() % 26];
} else if (pick < 85) { /* plain words */
runs = 1 + (unsigned)(next() % 5);
for (k = 0; k < runs; k++) {
if (k)
buf[used++] = ' ';
for (j = 0; j < 7; j++)
buf[used++] = alpha[next() % 26];
}
} else if (pick < 92) { /* an ideographic space */
buf[used++] = '\xe3';
buf[used++] = '\x80';
buf[used++] = '\x80';
} else if (pick < 97) { /* a no-break space */
buf[used++] = '\xc2';
buf[used++] = '\xa0';
} else { /* a combining accent, width zero */
buf[used++] = 'e';
buf[used++] = '\xcc';
buf[used++] = '\x81';
}
}
buf[used++] = '\n'; buf[used++] = '\n';
if (used + LINE_LEN + 1 > CHUNK) { /* a UTF-8 line is up to ~50 bytes, an ASCII line exactly 11 */
if (used + 128 > CHUNK) {
if (fwrite(buf, 1, used, stdout) != used) if (fwrite(buf, 1, used, stdout) != used)
return 1; return 1;
used = 0; used = 0;
+143 -26
View File
@@ -26,11 +26,17 @@ with the contract.
| lines, 1B (solo) | — | — | — | **266ms** | | lines, 1B (solo) | — | — | — | **266ms** |
| stdin lines, 10M | 5.9ms | 161ms | 154ms | **4.6ms** | | stdin lines, 10M | 5.9ms | 161ms | 154ms | **4.6ms** |
| stdin words, 1M | 7.1ms | 16.0ms | 16.5ms | **1.5ms** | | 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 That is a 13x win over GNU on 10M lines of words, 4.9x on 1M, and 1.6x
on the 100M monster. GNU's threaded counter manages a genuine dead on the 100M monster. `-L` used to be the exception — a serial walk that
heat at 110 MB of plain lines (5.8ms vs our 4.6ms — it never wins; lost to GNU on anything past a few megabytes. It is now the biggest win
we allow it a 2% tie margin and it still can't take it). The moment 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 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 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 fits — the solo run lands at 266ms: 41.4 GB/s, 3.76 billion lines per
@@ -124,26 +130,111 @@ half and then the honest reporting:
from a regular file (`fastwc -l < file`) gets the same treatment — 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 data comes through stdin, but how we read it is our business.
The stdin suite is why this shows up in the scoreboard too. The stdin suite is why this shows up in the scoreboard too.
3. **Parallel across cores.** Files over 8 MiB are split into 64-byte 3. **Parallel across cores, sized to the work.** A thread has to earn its
aligned slices counted by up to one thread per core (capped at 24) spawn, which costs about what counting 512 KiB costs, so a mapping
past 256 MiB, 12 past 32 MiB, 4 past 8 MiB. The kernels are pure, so gets one slice per 512 KiB (256 KiB for `-L`, whose kernel is several
the split needs no locks; word boundaries between slices are seeded times the work per byte), capped at the CPUs the process may actually
from the byte before the slice, which makes the split exact. Below use. That number comes from `sched_getaffinity`, narrowed by the
8 MiB the thread spawn would cost more than the counting, so we don't cgroup CPU quota when one is set, with `sysconf` as the last resort —
bother. `sysconf` answers for the whole machine, which is the wrong answer
4. **No work that isn't asked for.** `-c` on a regular file is under `taskset` and the wrong answer inside a container. The kernels
`st_size` from `fstat` — GNU figured that one out too, so we copied are pure, so the split needs no locks; word boundaries between slices
the good idea. `-l` without `-w` skips the whitespace mask entirely; are seeded from the byte before the slice, which makes the split
`-w` without `-L` never builds the print table. exact.
5. **ASCII pays nothing, even in a UTF-8 locale.** Multibyte decoding 4. **A long file list runs on a pool.** Past eight names, one worker per
is expensive, so we don't volunteer for it. The SIMD kernels core takes the next file and the rows are printed in argument order
double as a probe: when asked, they flag the first byte ≥ 0x80 when they finish. A thousand 1 MiB files spend nearly all their time
with a vector move-mask — no extra pass, no cost on pure-ASCII in the kernel, so the pool is the difference between 45 ms and 150 ms.
input. A file that stays pure ASCII keeps the full-speed byte The workers turn off per-file slicing: two layers of parallelism only
path, and its counts are identical to what the decoder would oversubscribe each other.
produce, because ASCII decodes to itself. Only files that actually 5. **`-L` folds by maximum.** A line's width depends on where the line
contain a high byte pay for the multibyte decoder, and then only starts, which looks like sequential state. It isn't: a slice that
from the first high byte on. 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-10 ms** | 11.6 ms | 223 ms |
| longest line, ASCII under UTF-8 | 21.7 ms | **9.5 ms** | 10.2 ms | 218 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 ## Correctness is the other half of the contract
@@ -163,12 +254,26 @@ oracles. Matching GNU byte for byte took some archaeology:
The selftest (`cc -DFASTWC_SELFTEST src/main.c`) checks every kernel The selftest (`cc -DFASTWC_SELFTEST src/main.c`) checks every kernel
against the scalar reference over all sizes, both carry states, and against the scalar reference over all sizes, both carry states, and
both counting modes, plus the threaded slice split. A randomized fuzz both counting modes, plus the threaded slice split. Every width kernel
against GNU as oracle (both locales, binary and UTF-8 data, every flag is checked the same way, from a line start and from a carried line
combination) passes 100%. 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 ## 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 - **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, `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. because 64 KiB pipe chunks trigger a re-scan of its carried bytes.
@@ -182,6 +287,18 @@ make bench # build release + run every suite
./benchmarks/test-all.sh # words, lines (monsters included), stdin ./benchmarks/test-all.sh # words, lines (monsters included), stdin
``` ```
The words suite ends with `-w`, `-m` and `-L` over 300k lines of mixed
UTF-8 under `en_US.UTF-8` (or `C.UTF-8`), raced against coreutils. The
suite pins the C locale for every other case, so without these the
decoder had no contract at all; the case skips with a printed note on a
host with no UTF-8 locale, because a multibyte count cannot be checked in
a single-byte one.
The lines suite races `-L` as well as `-l`, and ends by counting 128
files of about 1.1 MB each, which is the worker pool's case: both sides
finish in well over a second's worth of work, so the row is a race and
not a startup measurement.
`test-all.sh` compiles its two helper tools on the spot `test-all.sh` compiles its two helper tools on the spot
(`tools/genfile` for the test data, `tools/timeit` for microsecond (`tools/genfile` for the test data, `tools/timeit` for microsecond
timing) — no separate setup. The suites live in timing) — no separate setup. The suites live in
+1734 -95
View File
File diff suppressed because it is too large Load Diff