r/learnrust • u/hrubydavid • Oct 23 '26
Leveling up in Rust by following Jon Gjengset's One Billion Row Challenge stream. Join me?
Hi all.
I would like to be a Rustacean. I have done some theory and Rustlings again. From time to time I started with Rust and did some prototypes but this time I really want to do Rust every day.
I like practice and challenges so I am following Jon Gjengset's One Billion Row Challenge ~10.5 hours stream recording and programming it too. I am trying to measure and document all the results and what I have learnt.
But I think it would be even more fun in a group. So if you are new to Rust or would like to show your approach I would be super happy to discuss it here.
I have never created such a group so cannot say what it should look like. It could be the way that everybody can share execution time of Jon's final solution on his machine as the baseline benchmark. Jon was able to run it on his computer with time 1.077 seconds. I was able to run his code with time 14.51 seconds because my computer is MacBook Air (Mac16,12) Apple M4, 10 cores (4 performance + 6 efficiency) 16 GB RAM.
What do you think? Even the later joiners are welcome.
1
u/hrubydavid Oct 25 '26
I am about to start the mmap part now 🥳 My yesterday's version finished the execution in 109 seconds and here are my today's changes following Jon's stream:
HashMap instead of BTreeMap, sorted only for the output: 77.0 s
get_mut first, no new String for every line: 66.3 s
Bytes instead of strings, Vec<u8> keys: 53.4 s
from_utf8_unchecked, no UTF-8 check: 51.7 s
lto = "fat" in the release profile: 48.6 s
Detail info: https://github.com/davidhruby/brrr/blob/part003/docs/part003-hashmap-bytes-and-lto.md
Actual code: https://github.com/davidhruby/brrr/blob/part003/src/david/main.rs
1
u/hrubydavid Oct 29 '26
mmap was harder as I hit the limit of my RAM again. My machine has 16 GB RAM in total and the input file has ~13GB. But I enjoyed it a lot 🥳 I am happy I can keep up with Jon even my hardware is limited.
The changes:
1. mmap instead of BufReader
half the instructions per row (1B ~940 → ~477) and the CPU time on 1B dropped from 48 s to 28 s. But the wall time on 1B stayed the same (48.6 s → 47 s): the program now spends ~19 s waiting for the SSD 😬
2. MADV_WILLNEED on the whole file
wall time 47 s → 63 s. Most of the file is read twice. The system runs out of RAM and drops pages before the program gets to them so the page faults jump from 842_023 to 1_671_039.
3. MADV_WILLNEED in 512 MB chunks + MADV_DONTNEED behind
wall time 47 s (change #1) → 37 s 🥳 The waiting dropped from ~19 s to ~9 s.
4. A helper thread that touches the pages ahead
wall time 37 s → 28 s 🥳 🥳 wall time is now about the CPU time. Threads of one process share the page tables so when the main thread gets to a page it is already mapped.
--------------------------------------------------------------------------------------------------------
At the end I did a small refactoring and added a few unit tests to have the structure I like.
More details: https://github.com/davidhruby/brrr/blob/part004/docs/part004-mmap.md
Code: https://github.com/davidhruby/brrr/blob/part004/src/david/main.rs
1
u/hrubydavid Oct 31 '26
This part was about parsing the temperature and I went down a rabbit hole of branch mispredictions 🥳
The changes:
1. Temperatures as integers in tenths, parsed by hand instead of parse::<f32>()
wall time on 1B 28 s → 25.4 s. About 75 fewer instructions per row (~484 → ~410).
2. A benchmark for the parser (criterion)
per input, on 10,000 random temperatures: parse::<f32>() 8.96 ns, my loop with match 2.79 ns, a version without branches 1.12 ns 🥳
pub fn parse_temperature(temperature: &[u8]) -> i16 {
let is_negative = (temperature[0] == b'-') as usize;
let digits = &temperature[is_negative..];
let len = digits.len();
let tenths = (digits[len - 1] - b'0') as i16;
let ones = (digits[len - 3] - b'0') as i16;
let tens = (digits[0] - b'0') as i16 * (len == 4) as i16;
let value = tens * 100 + ones * 10 + tenths;
// is_negative has 0 or 1 value therefore 1 - (2 * 0) = 1, 1 - (2 * 1) = -1
value * (1 - (2 * is_negative as i16))
}Perf test code: https://github.com/davidhruby/brrr/blob/part005/benches/parse_temperature.rs
3. Parsing without branches (fixed positions from the end, no loop, no if)
wall time 25.4 s → 24.7 s. Much less than the benchmark promised: on the real data the branch predictor guessed my loop right most of the time so it saved only ~0.1 mispredictions and ~6 % of the cycles per row.
More details: https://github.com/davidhruby/brrr/blob/part005/docs/part005-parsing-temperature.md
Code: https://github.com/davidhruby/brrr/blob/part005/src/david/main.rs
1
u/hrubydavid Nov 05 '26
Hi all. Sorry for a few days of silence but I've been playing with performance tests a lot 💪 I got so hooked that I already did the ';' and '\n' in one pass which Jon does later in his video. From Part 005 it's 24.7 s → 18.5 s (−25 %). The switch to nightly Rust (for std::simd) alone made only ~1 %.
This part was about finding the end of a line, and I learned when SIMD pays off and when it doesn't.
The changes:
1. memchr instead of split for finding the '\n'
wall time on 1B 24.7 s → 23.9 s. memchr already uses SIMD (NEON, 16 bytes at once), but a line is only ~14 bytes, so every call pays mostly for the call itself and the setup.
2. Finding the '\n' 8 bytes at a time in a normal u64 register (SWAR)
wall time 23.9 s → 21.0 s per line on the 1M file: split 9.4 ns, memchr 7.9 ns, SWAR 4.9 ns. No call into the library, just a few instructions right in the loop.
3. An attempt: finding the ';' with u8x64 (portable SIMD, nightly)
6× slower than rsplitn (17.0 ns vs 2.7 ns per line) 😬 load_or_default copied every short line into a 64-byte buffer first, and rsplitn only looks at the last 4 – 6 bytes anyway.
4. Finding the ';' and the '\n' of several lines at once (SIMD iterator)
wall time 21.0 s → 18.5 s 🥳🥳 One 64-byte block holds 4 – 5 lines, so I load it once, compare it with ';' and with '\n', keep both results as bit masks, and take one line after another with trailing_zeros and mask &= mask - 1. Per line: SWAR + rsplitn 6.03 ns, one SIMD block per line 5.15 ns (u8x32), the iterator 2.85 ns.
if self.newline_bit_mask == 0 {
self.block_start = self.at;
let simd_value = u8x64::from_slice(&self.map[self.at..self.at + 64]);
self.delimiter_bit_mask = DELIMITER.simd_eq(simd_value).to_bitmask();
self.newline_bit_mask = END_LINE.simd_eq(simd_value).to_bitmask();
}
let delimiter_index = self.delimiter_bit_mask.trailing_zeros() as usize;
self.delimiter_bit_mask &= self.delimiter_bit_mask - 1;
let newline_index = self.newline_bit_mask.trailing_zeros() as usize;
self.newline_bit_mask &= self.newline_bit_mask - 1;More details: https://github.com/davidhruby/brrr/blob/part006/docs/part006-finding-the-end-of-a-line.md
Code: https://github.com/davidhruby/brrr/blob/part006/src/david/main.rs
1
u/hrubydavid 28d ago
My Part 007 is about hashing. The HashMap with the default hasher (SipHash) had become the biggest cost. Over half of the main thread's time in the profile and ~62 % of the branch mispredictions.
Found very interesting video during my play: Faster than Rust and C++: the PERFECT hash table
The changes:
1. Playing with hashers
I tried several hashers in a benchmark of the HashMap alone (rows split and parsed in advance). The numbers moved between runs, so each one is next to SipHash from the same run, per row:
Sum of the bytes: 25.4 ns vs SipHash 12.2 ns 😅
Folded multiply, 8 bytes at a time, with a typo (& instead of ^): 36.2 ns vs 12.0 ns 😬
Folded multiply, 8 bytes at a time: 19.0 ns vs 12.0 ns
FastHasher (the rest of the name as one more padded block): 11.6 ns vs 14.7 ns
IdealHasher: 10.7 ns vs 14.7 ns 🥳
2. Counting the collisions, and the capacity of the HashMap
I wrote a small tool that counts for the 413 station names. Two things:
how many buckets get more than one name
how many groups of names share the bucket and the tag (expensive because hashbrown needs comparing names)
Results:
512 buckets (HashMap::new()): SipHash 98 shared buckets and 2 groups with the same bucket and tag; FastHasher 98 shared buckets and 2 groups with the same bucket and tag
2_048 buckets: SipHash 41 shared buckets and 0 groups with the same bucket and tag; FastHasher 36 shared buckets and 1 group with the same bucket and tag
16_384 buckets (with_capacity(10_000)): SipHash 6 shared buckets and 0 groups with the same bucket and tag; FastHasher 8 shared buckets and 1 group with the same bucket and tag
4_194_304 buckets: SipHash 0 shared buckets and 0 groups with the same bucket and tag; FastHasher 1 shared bucket and 1 group with the same bucket and tag
Wall time improvements from 18.5 s → 13.6 s (−26 %).
More details: https://github.com/davidhruby/brrr/blob/part007/docs/part007-hashing.md
Code: https://github.com/davidhruby/brrr/blob/part007/src/david/main.rs
1
u/hrubydavid 23d ago
No speedup in Part 008 – 009. Instead I left my MacBook for a few days and rented machines on AWS. My M4 has 16 GB of RAM so the 13.8 GB file doesn't fit there and macOS doesn't give me the Linux perf counters (dTLB misses, branches) that Jon was looking at. So I tested on three instances, each with 32 GB, with the 1B file in a tmpfs RAM disk:
AWS Graviton3 (ARM, r7g.xlarge)
Intel Sapphire Rapids (x86)
AMD Zen 5 (x86, r8a.xlarge)
The changes:
1. StrVec: station names stored inside the key (after Jon)
A name shorter than 16 bytes lives right in the 16-byte key no heap. On my MacBook, 1B went from 13.6 s to 14.1 s (slower). Comparing short keys as one u128 gave 14.8 s (even slower). With 413 short names in the L1 cache there was nothing to save. Back to Vec<u8>.
2. Why is Jon's code 4.6× slower on the Graviton3? (88.6 s vs 25.05 s on his PC)
On ARM u8x64::load_or_default compiles to up to 64 single-byte loads. ARM has no masked load but x86 with AVX-512 does it in one instruction. The load alone, per line:
Graviton3: 25.78 ns
Intel, generic build: 32.72 ns
Intel, -C target-cpu=native (AVX-512): 1.81 ns 🤯
Same CPU but 18× faster only from a compiler flag. Jon's whole program on 1B: Intel 62.29 s → 36.85 s. Zen 5 40.03 s → 22.31 seconds. His 19.17 s of user time fits only an AVX-512 build.
My code loads whole 64-byte blocks and doesn't need the masked load: 10.0 s on Zen 5.
3. dTLB misses, which Jon complained about
They come from the size of the HashMap and not from StrVec 🤯 Jon creates it with with_capacity(100_000). That's 131_072 buckets and ~6.4 MB. The 413 stations land nearly one per 4 KB page. That's ~390 pages and more than the L1 dTLB holds. On Zen 5 it gives ~1.06 misses per row of the file. With with_capacity(10_000) the table is 8× smaller and it's ~0.52.
Do they cost anything? With huge pages (2 MB instead of 4 KB) the misses dropped by ~75 %. The program wasn't any faster. So they cost almost nothing 🤔
Wall time on my MacBook stays at 13.6 s (back to the Part 007 code).
More details:
https://github.com/davidhruby/brrr/blob/part008/docs/part008-short-strings.md
https://github.com/davidhruby/brrr/blob/part009/docs/part009-masked-loads-and-dtlb-misses.md
Code: https://github.com/davidhruby/brrr/blob/part009/src/david/main.rs
1
u/hrubydavid 22d ago edited 22d ago
Part 010 – 012. On my MacBook 1B went from 13.6 s to 9.88 s on one thread. Then I added threads and moved to AWS.
The changes:
1. Comparing station names with SIMD instead of memcmp
memcmp was ~35 % of the xctrace profile. hashbrown compares the names with [u8] == [u8] and that calls memcmp. I wrote my own PartialEq: load 16 bytes of both names as u8x16 and mask out the bytes after the end of the name.
14.01 s → 10.17 s (−27 %). With only u8x16 and no 32/64-byte branches: 9.93 s.
2. Branches instead of min()/max() (idea from barrcodes and curiouscoding)
A new minimum or maximum comes only a few times per station so the branch predictor almost never misses. −2.4 % instructions and ~−1 % cycles. 9.93 s → 9.88 s.
3. Threads 🚀
The file is split into equal chunks (each ends at a \n) and every thread has its own HashMap. The main thread merges them at the end. That's 413 stations per thread so microseconds.
On my MacBook it was slower than one thread. The SSD is the limit already with one thread (~1.4 GB/s) and 4 threads reading at 4 places made the reads tiny (~20 KB). So I measured like the original challenge did: 8 cores and the file on a RAM disk. AWS r8a.2xlarge (AMD Zen 5, 8 cores, 64 GB RAM) with the 1B file in tmpfs.
Scaling is almost linear up to 8 threads. 1 thread 10.68 s → 8 threads 1.36 s.
4. Huge pages for tmpfs
With 8 threads I lost ~13 % against the ideal time. The cause was the 4 KB pages of the file: page walks (up to ~3× more at the end of the file depending on where the copy landed in memory).
And one surprise I asked about separately: removing eprintln! made my hot loop 11 % slower 🤔 https://www.reddit.com/r/rust/comments/1xvohjp/removing_eprintln_made_my_hot_loop_11_slower_how/
Wall time: 13.6 s on one thread on my MacBook → 1.36 s on 8 threads on AWS.
More details:
https://github.com/davidhruby/brrr/blob/part011/docs/part011-ideas-from-other-solutions.md
https://github.com/davidhruby/brrr/blob/part012/docs/part012-threads-and-4kb-pages.md
Code: https://github.com/davidhruby/brrr/blob/part012/src/david/main.rs
1
u/hrubydavid 18d ago
Part 013: my own hash table. Same AWS Zen 5, 1B file in tmpfs: 8 threads 1.36 seconds → 0.809 seconds 🥳
The changes:
1. A floor first
I replaced the lookup with stats[name.len]: no hash. no comparison. The output is wrong on purpose. It shows the best any table could do: hashbrown was ~64 % of my cycles.
2. Own hash table
The first 16 bytes of the name as two u64s and a multiply hash and linear probing. Mispredictions −59 %,. Cycles −26 %.
3. A bigger table
2,048 → 16,384 slots. Every doubling halved the probing mispredictions and each one costs ~35 cycles here. −12 %.
4. Box<[Slot; N]> instead of Vec
The length is in the type so the bounds checks are gone. That's only one well-predicted branch per row and it still gave −5.5 % 🤯 Gotcha: Box::new([...; N]) builds the array on the stack first.
And the eprintln! mystery from last time: #[inline(always)] on one fixed it. Thanks for the comments!
Wall time: 1.36 s → 0.809 s on 8 threads.
More details: https://github.com/davidhruby/brrr/blob/part013/docs/part013-own-hash-table.md
Code: https://github.com/davidhruby/brrr/blob/part013/src/david/main.rs
1
u/hrubydavid 10d ago
Part 014: the hot loop. Same AWS Zen 5, 1B file in tmpfs: 8 threads 0.809 seconds → 0.499 seconds.
The changes:
1. A hash without collisions
I searched for a multiplier that gives no collision on the 413 names of the data. Only −1.4 %, because probing was already rare with 16,384 slots.
2. #[inline(always)] on the iterator's next
It was a function call for every row. −11 % cycles.
3. -C target-cpu=znver5
The search for ; in a block of 64 bytes was 4 SSE loads and compares. With AVX-512 it's one. −10 %.
4. A key of 32 bytes
The whole name is in one AVX register so there's one compare instead of two u64 words plus memcmp for long names. −8.6 %.
5. Smaller ones
A SWAR parser for the temperature, the table on a 2 MB huge page, the hash from the first 8 bytes and the length, and a fast loop without the end-of-chunk checks.
Wall time: 0.809 s → 0.499 s on 8 threads.
More details: https://github.com/davidhruby/brrr/blob/part014/docs/part014-zero-collisions.md
Code: https://github.com/davidhruby/brrr/blob/part014/src/david/main.rs
1
u/hrubydavid 3d ago
Part 015: PGO and one line. Same AWS Zen 5, 1B file in tmpfs: 8 threads 0.497 seconds → 0.398 seconds.
The changes:
1. PGO with cargo-pgo
Thanks for the tip in the comments. −6.6 % cycles and 0.467 s without touching the code. I wanted to know why so I compared the assembly with and without PGO. The layout of the code didn't matter. What mattered was the registers: without PGO 11 loads and stores to the stack per row. With PGO 2.
2. The same with one std::hint::cold_path()
The cause was one branch: the compare of names longer than 32 bytes, which calls bcmp. The compiler assumed that call happens half of the time and spilled the loop state to the stack to make room for it. One cold_path() in that branch gives the same result with a plain cargo build: 16.33 cycles per row and 0.464 s. PGO on top of it was slower so I don't use PGO.
3. The next block without a branch
Loading the next block of 64 bytes when the mask of ; ran out was the last branch that mispredicted: a block holds 4 – 5 rows but how many depends on the lengths of the names. Now the mask of the next block is computed in advance on every row and switched in with two cmovs (std::hint::select_unpredictable). Mispredictions dropped from 0.111 to 0.0001 per row, cycles from 16.33 to 12.75 (−22 %), even with 10 more instructions per row. 5.8 instructions per cycle.
Wall time: 0.497 s → 0.398 s on 8 threads. On the same instance the winner of 1BRC (thomaswue, Java) takes 0.514 s.
More details: https://github.com/davidhruby/brrr/blob/part015/docs/part015-pgo.md
Code: https://github.com/davidhruby/brrr/blob/part015/src/david/main.rs
1
1
u/Beneficial_Vampire42 Oct 24 '26
I tried it before, it was pretty cool!
One thing you probably need is a big enough RAM to load the file before the the actual program runs and mount the memory so it looks like a file. Otherwise the endgame optimizations just don't show up in numbers. That's the only pain point I had with setup.
Check it out if you are curious (be aware, spoilers) https://github.com/barakugav/frenzy
1
u/hrubydavid Oct 24 '26
Cool. Thank you for sharing. Will take a look deeper. Do you have some your improvements there? And what was your execution time, please?
2
u/Beneficial_Vampire42 Oct 24 '26
I tried to explain the improvements I used in the readme.
I don't remember the exact time, but it will also just be a measurement on my computer, better to compare to other impls on the same machine. It was comparable to the top5 of the original java leaderboard
1
u/hrubydavid Oct 25 '26
Cool. Happy you committed that in multiple commits so I can compare my evolution with your too 👍
1
u/hrubydavid Oct 24 '26
I don't have enough ram on my computer but I take it as another challenge though. I may try spin up cloud instance or my old intel machine with 64GB RAM. Will see.
1
u/hrubydavid Oct 24 '26
My first version (the naive one) was based on std::fs::read_to_string which reads the entire contents of the 1BRC file into memory. That was a problem as I have only 16GB RAM in total. Actually free RAM is about ~3GB. It took 266 seconds as it was swapping a lot.
After switching to BufReader and a few nice-to-have code improvements it takes 109 seconds with 1.9 MB memory usage.
Here is the link to the code (the naive version): https://github.com/davidhruby/brrr/blob/part002/src/david/main.rs
I spent most of today's fun on this investigation and documentation: [Rust Gotchas: HashMap entry: or_insert or or_insert_with?](https://www.reddit.com/r/rust/comments/1xelb3t/rust_gotchas_hashmap_entry_or_insert_or_or_insert/)