From 7 Milliseconds to 37 Microseconds: Counting 33 Million Squares in C++
A ground-up, zero-jargon guide to high-performance C++ optimization on Advent of Code 2026 Day 3 — evolving a 4-loop brute-force solver through sparse pruning, CPU branch prediction, bitboards, shifted bit-planes, L1 cache tiling, and 512-bit Zen 5 AVX-512 SIMD.
On this page
- 1. What the Puzzle Actually Asks (And How to Spot Any Square Without Trig)
- 2. My First Three Attempts (6.76 ms → 2.94 ms → 1.65 ms)
- 3. Why 1.65 ms Hits a Wall: A Friendly Tour Inside Your CPU
- 4. Stage 4: Bitboards, Exact Algebra & TZCNT Bit-Jumping (1,650 µs → 474 µs)
- 5. Stage 5A: Solving All of Part 1 in 1.30 µs with Two Bitwise ANDs
- 6. Stage 5B: The Big “Aha!” — Turning Tilted Squares into Shiftless Bit-Planes (474 µs → 121 µs in Pure C++23)
- 7. Stage 6: Hitting 37.5 µs on Zen 5 (~160 Squares per Clock Cycle)
- 8. Bonus Plot Twist: Reading the 20 KB File Took 2.5× Longer Than Solving the Puzzle
- 9. Six Lessons You Can Steal for Any High-Performance Code
I’ve been doing Advent of Code 2026 by hand in C++23 to keep my brain sharp and practice writing fast, low-level code. When Day 3 dropped, my first working solution ran in about 6.8 milliseconds (-O3, or 51 ms in a Debug build). After two quick algorithmic tweaks — collecting # coordinates into a std::vector and only scanning the upper triangle of pairs — it dropped to 1.65 milliseconds.
Under two milliseconds feels pretty good. Most people stop there and go to bed.
Instead, we decided to ask a fun question: how fast can a single CPU core physically solve this puzzle if we refuse to stop until we hit silicon limits?
By the time the dust settled on one core of an AMD Ryzen 9 9950X3D (Zen 5), the exact same puzzle — parsing all 20,161 ASCII bytes from memory and counting both Part 1 and Part 2 across 32,936,190 candidate squares — ran in:
37.5 microsecondsmedian (35.9 µsmin) for Part 1 + Part 2 (180× faster thanv1, 44× faster thanv3— faster than Windows NTFS takes just to open theinputfile!)1.30 microsecondsmedian (1.20 µsmin) for Part 1 alone (~769,000 full solves per second on a single core)121.1 microsecondsmedian using 100% portable standard C++23 with zero SIMD intrinsics (55.9× faster thanv1)
Here is the full optimization scoreboard before we start from square one:
1. What the Puzzle Actually Asks (And How to Spot Any Square Without Trig)
The Input Grid
The puzzle gives you a square 141 × 141 ASCII grid (19,881 cells total). Every cell is either empty ground (.) or a tree (#). In my puzzle input, 1,704 cells are # — a density of 8.57% (roughly 1 tree every 12 cells).
- Part 1: How many axis-aligned squares (flat horizontal top/bottom, vertical left/right sides, of any size
1×1up to140×140) have#trees at all four corners? (Answer:415) - Part 2: How many squares of ANY angle — flat or tilted diagonally at any slope! — have
#trees at all four corners? (Answer:2,553— the415flat squares plus2,138tilted ones)
Wait — How Do You Check Tilted Squares Without Sines, Cosines, or Floats?
At first glance, “tilted at any angle” sounds nasty. Do you have to loop over angles , call sin and cos, and worry about floating-point rounding?
Nope. Pure integer addition and subtraction is all you ever need.
Imagine pinning down one corner of a square on graph paper at , and picking a second corner at :
- To walk along the top-right edge from to , you step right by
dx = rx - xand down bydy = ry - y. (Remember: in grid coordinates,xgrows to the right andygrows downward.) - How do you turn clockwise on graph paper without trigonometry? Swap the two step numbers and flip one sign! Stepping “right
3, down1” (+dx, +dy) rotated becomes “left1, down3” (-dy, +dx). - Start back at and take that -rotated step
(-dy, +dx)to land on the third corner: - From , take the original step
(+dx, +dy)once more to close the bottom corner of the square:
Let’s plug in real numbers on an 8 × 8 toy grid so there is zero mystery. Pick and :
dx = 6 - 3 = 3,dy = 2 - 1 = 1.- .
- .
Check the four sides: every single side moves (3, 1) or (-1, 3), so every side has length , and their dot product is (!). No square roots, no floats, just four int additions.
How Do We Guarantee We Count Every Square Exactly Once?
Every square has 4 corners, which means there are pairs of corners you could stumble across while looping. If we aren’t careful, we’ll count the same square 4 or 8 times!
One tiny rule fixes this completely: require dx > 0 and dy >= 0. Why does that make every square unique?
- Case A — Flat square (
dy == 0, dx > 0):- (top-left)
- (top-right)
- (bottom-left)
- (bottom-right)
Every flat square has one unique top-left corner, so
dy == 0, dx > 0hits it once — and gives us Part 1!
- Case B — Tilted square (
dy > 0, dx > 0): Look at they(row) coordinates of the 4 corners when bothdx > 0anddy > 0: has a strictly smallerythan all three other corners! Every tilted square has one unique highest corner on the grid, and from that highest corner, is the unique adjacent corner going down-and-right (dx > 0, dy > 0). Every tilted square in the universe is hit at most once!
2. My First Three Attempts (6.76 ms → 2.94 ms → 1.65 ms)
Attempt 1 (v1): The Brute-Force 4D Grid Scan (6,764 µs -O3)
My first instinct was the most direct translation of the math above: loop (x, y) over every cell of the 141 × 141 grid, and whenever (x, y) is a #, loop (rx, ry) over the sub-grid below and to the right of (x, y):
// v1: 6,764 µs (-O3) / 51,038 µs (Debug)
for (int y = 0; y < 141; ++y) {
for (int x = 0; x < 141; ++x) {
if (!occupied(x, y)) continue;
for (int ry = y; ry < 141; ++ry) {
for (int rx = x; rx < 141; ++rx) {
if (!occupied(rx, ry)) continue;
const int dx = rx - x;
if (dx == 0) continue;
const int dy = ry - y;
const int p2x = x - dy, p2y = y + dx;
if (!valid(p2x, p2y)) continue;
const int p3x = p2x + dx, p3y = p2y + dy;
if (!valid(p3x, p3y)) continue;
if (occupied(p2x, p2y) && occupied(p3x, p3y)) {
if (dy == 0) ++aa_squares;
else ++o_squares;
}
}
}
}
}Why is v1 doing 7 milliseconds of work?
Because only 8.57% of the grid has # trees! For each of the 1,704 outer # trees, the inner (rx, ry) loops walk across ~5,000 grid cells on average — around 8.5 million inner iterations, and 91.4% of them (~7.8 million iterations) land on empty . dirt and immediately continue!
Attempt 2 (v2): Collect # Coordinates First (2,935 µs — 2.3× Faster)
Why check 7.8 million empty . cells when we can walk the grid once, push all 1,704 # coordinates into std::vector<Tree> trees, and only loop over trees × trees?
1,704 × 1,704 = 2,903,616pairs — zero empty.cells ever touched!- Runtime immediately dropped in half:
6,764 µs→3,538 µs(-O3) /2,935 µs(-march=native).
Attempt 3 (v3): Only Scan the Upper Triangle k = i (1,650 µs — 4.1× Faster)
Look at how trees was built: we scanned y from 0 to 140, and inside each row, x from 0 to 140. That means trees is already sorted from top to bottom!
In v2, when our inner loop started at k = 0, every index k < i was above trees[i] (ry < y), so dy < 0 threw away the entire first half of trees! Changing literally one character (k = 0 → k = i):
// v3: 1,772 µs (-O3) / 1,650 µs (-march=native)
for (size_t i = 0; i < trees.size(); ++i) {
const auto [x, y] = trees[i];
for (size_t k = i; k < trees.size(); ++k) {
const auto [rx, ry] = trees[k];
const int dx = rx - x, dy = ry - y;
if (dx <= 0 || dy < 0) continue;
// ... same p2, p3 check ...
}
}cut the inner loop iterations in half again (2.90M → 1,450,956 pairs), cutting runtime in half again to 1.65 ms.
Play with the interactive grid below! Hover or tap any # tree to see the exact cells/pairs tested by v1, v3, and our upcoming Bitboard + TZCNT stage — or flip Paint # cells on to draw your own squares and watch the vectors update live:
3. Why 1.65 ms Hits a Wall: A Friendly Tour Inside Your CPU
To get from 1,650 microseconds down to 37.5 microseconds (44× faster than v3!), we can’t just tweak loop indices anymore — we have to look at what the physical silicon inside the Ryzen 9 9950X3D is doing on every clock tick.
If you’ve never studied CPU microarchitecture, don’t sweat it. Everything we are about to do boils down to five plain-English hardware facts:
| Hardware Concept | Plain-English Analogy | Zen 5 Reality (Ryzen 9 9950X3D) |
|---|---|---|
| Clock Cycle | One “heartbeat” of a CPU core. At 5.5 GHz, 1 cycle is 0.18 nanoseconds (5,500 cycles per microsecond!). | Modern cores don’t run 1 instruction per cycle — Zen 5 can retire up to 6–8 instructions in a single cycle if nothing stalls it! |
| Branch Predictor | A high-speed freight train approaching a Y-junction before the switch signal arrives: the CPU guesses whether an if is true or false and speculative-executes 100+ instructions ahead. | Guess right (99% predictable loop): 0 penalty. Guess wrong (50/50 coin-flip if): ~14–18 cycle pipeline flush — throwing away all speculative work! |
| Cache Hierarchy | Your desk (Registers, 0–1 cy) → backpack (48 KB L1D, ~4 cy) → bedroom shelf (1 MB L2, ~12 cy) → warehouse across town (RAM, ~200+ cy). | Keeping our grid inside 48 KB L1D feeds two 64-byte loads every single cycle. Spilling into L2 cuts bandwidth 3–4×. |
| Bitboard (SWAR) | SIMD Within A Register: instead of wasting an entire 8-byte char (8 bits) or int (32 bits) to store one yes/no #, pack 64 #/. cells into the 64 bits of one uint64_t. | One bitwise & instruction tests 64 grid cells in 1 cycle instead of 1 cell! |
AVX-512 (__m512i) | Extra-wide 512-bit hardware registers (zmm0..zmm31). One register holds 8 × uint64_t = 512 bits at once! | Zen 5 has true single-cycle 512-bit execution units (4 vector ALU pipes + 2 × 64-byte load pipes + hardware 512-bit VPOPCNTDQ). |
Auditing the Crime Scene Inside v3
Now look back at v3’s inner loop (1,450,956 pairs of trees (i, k) with k >= i) with your new CPU X-ray goggles on:
- Crime #1 —
if (dx <= 0)is a literal 50/50 coin toss (725,000random outcomes!): Becausetrees[k]is on a lower row thantrees[i], its horizontal positionrxis just as likely to fall left ofx(dx <= 0) as right ofx(dx > 0). Every time the CPU’s branch predictor guesses wrong on that coin flip, it flushes ~15 cycles of work down the drain! - Crime #2 —
valid(p2)andvalid(p3)reject 67% of what’s left: Even whendx > 0, two-thirds of the remaining725,000pairs throw or off the left, right, or bottom edge of the141 × 141board! Out of1,450,956loop iterations, only~241,000(16.6%— 1 in 6!) are even geometrically allowed to form a square inside the grid! - Crime #3 — Testing 1 square at a time:
Checking
occupied(p2)andoccupied(p3)tests one single square per iteration while 511 out of 512 bits of our CPU’s vector hardware sit dark.
Let’s fix Crimes #1 and #2 first using pure, portable C++23 — before we even touch SIMD.
4. Stage 4: Bitboards, Exact Algebra & TZCNT Bit-Jumping (1,650 µs → 474 µs)
Step 4A: Packing the Grid into Bits (20 KB → 3.3 KB)
Right now, storing the grid as a std::string uses 1 byte (8 bits) per character (20,161 bytes). Yet every cell only answers a 1-bit question: “Is there a # here (1) or not (0)?”
On an 8-cell toy row, packing . and # into bits looks like this (putting column 0 in bit 0, the rightmost bit):
Column x: 0 1 2 3 4 5 6 7
Grid chars: . . # . . # # .
Bits (0/1): 0 0 1 0 0 1 1 0 ──► uint8_t mask = 0b01100100 (binary)
= 100 (decimal)Our real row is 141 columns wide. One uint64_t holds 64 bits, two hold 128 bits, and a third holds the remaining 13 bits (64 + 64 + 13 = 141 bits, with bits 13..63 of the third word left at 0):
uint64_t row[141][3] = {}; // 141 rows × 24 bytes = 3,384 bytes total (3.3 KB!)How do you check if column x on row y is a #?
- Divide
xby64(x >> 6) to pick word0,1, or2. - Take the remainder
x % 64(x & 63) to pick the bit inside that word:
auto test_bit = [&](int x, int y) -> bool {
return (row[y][x >> 6] >> (x & 63)) & 1ULL;
};The entire 141 × 141 map now occupies 3.3 KB — less than 7% of Zen 5’s 48 KB L1 data cache!
Step 4B: Pre-Solving All 6 Bounds Checks with High-School Algebra
Instead of visiting pairs (x, y) and (rx, ry) and asking if (!valid(p2) || !valid(p3)) continue; a million times, let’s solve the inequalities once before entering the loop!
Suppose we are standing on a tree and looking for tilted squares (dx >= 1, dy >= 1, where dx = rx - x and dy = ry - y). What must ry and rx satisfy so all 4 corners stay inside [0, 140]?
- Leftmost corner must have :
(Bonus: if
x == 0, thenry <= y, which is impossible fordy >= 1— so column0can never be the top corner of a tilted square!) - Bottom corner must have :
Since
dx >= 1, we definitely need . And substitutingdx = rx - x: - Wait — what about ‘s
y-bound () and ‘sx-bound ()? Check them!- Since
ry > yand , we automatically have ! - Since
rx >= x + 1anddy <= x(from rule #1!), we automatically have , and !
- Since
Read that again: simply looping ry up to min(139, y + x) and restricting rx to [x + 1, min(140, 140 + x - ry)] guarantees 100% of all four corners are in-bounds without a single if statement!
Step 4C: Teleporting From # to # with std::countr_zero (TZCNT)
Even better: once we know valid rx values on row ry lie in [x + 1, max_rx], we don’t loop for (int rx = x + 1; rx <= max_rx; ++rx)! We slice out those bits of row[ry] with a bitmask m, and let two 1-cycle CPU instructions teleport straight from one # bit to the next:
std::countr_zero(m)(TZCNT— Trailing Zero Count): Counts how many0bits sit to the right of the lowest1bit — which is the exact column index of that1bit!m &= m - 1(BLSR— Reset Lowest Set Bit): Clears that lowest1bit to0so the next iteration jumps straight to the next#!
If you’ve never seen m & (m - 1) in binary before, watch what subtracting 1 does to m = 0b00101000 (which has # trees at bit 3 and bit 5):
m = 0 0 1 0 1 0 0 0 ◄── std::countr_zero(m) = 3 (three trailing zeros → column 3!)
m - 1 = 0 0 1 0 0 1 1 1 ◄── borrowing flips bit 3 to 0 and trailing 0s to 1s
────────────────────────────────
m & (m-1) = 0 0 1 0 0 0 0 0 ◄── bit 3 is gone! Next countr_zero() jumps straight to 5!Zero empty . cells visited, zero dx <= 0 coin-flip mispredictions, zero valid() branches. Pure standard C++23 drops from 1,650 µs to 474.1 µs (484.9 µs even on generic -O3 without -march=native — 14.3× faster than v1!).
5. Stage 5A: Solving All of Part 1 in 1.30 µs with Two Bitwise ANDs
Before tackling tilted squares with SIMD, pause and look at Part 1 (flat axis-aligned squares of side between top row y and bottom row y + d).
Suppose d = 3 on an 8-column toy grid, and compare Row y against Row y + 3:
Column x: b0 b1 b2 b3 b4 b5 b6 b7
R[y] (top): 0 1 1 0 1 1 0 1
R[y + 3] (bottom): 1 1 0 0 1 1 0 1
───────────────────────────────────────────────────
M = R[y] & R[y+3]: 0 1 0 0 1 1 0 1 ◄── '1' wherever BOTH top & bottom have '#'Look closely at M:
- Bit
1is1→ column1has#on both top and bottom. - Bit
4is1→ column4(= 1 + 3!) also has#on both top and bottom! Together, columns1and4form a3 × 3square! - Bit
2is0, wait — what about columns4and7(= 4 + 3)? Both bit4and bit7are1inM— that’s a second3 × 3square on the exact same row pair!
How do we find every column x where both bit x and bit x + 3 are 1 in M, all at once? Shift M right by 3 slots (M >> 3) so bit x + 3 lands directly on top of bit x, and AND them together!
Column x: b0 b1 b2 b3 b4 b5 b6 b7
M: 0 1 0 0 1 1 0 1
M >> 3: 0 1 1 0 1 0 0 0 ◄── bit 4 moved to b1; bit 7 moved to b4!
───────────────────────────────────────────────────
S = M & (M >> 3): 0 1 0 0 1 0 0 0 ◄── TWO 3×3 squares found at x=1 and x=4!Now call std::popcount(S) (POPCNT — a 1-cycle CPU instruction that counts how many 1 bits are in an integer), which returns 2.
Let that sink in: two &s, one shift, and one popcount just tested 64 columns in parallel! Across a 141 × 141 grid, there are only pairs of rows (y, y + d). Vectorizing 8 row-pairs at a time in AVX-512 solves all of Part 1 — including parsing the 20 KB input buffer — in 1.30 microseconds (~769,000 full solves per second on a single core!).
6. Stage 5B: The Big “Aha!” — Turning Tilted Squares into Shiftless Bit-Planes (474 µs → 121 µs in Pure C++23)
Step 1: Anchor at the Leftmost Corner (x' = x - dy) to Kill Negative Shifts
Look at the 4 column coordinates of a tilted square when anchored at the top corner :
- : column
x(on rowy) - : column
x + dx(on rowy + dy) - : column
x - dy(on rowy + dx) ← annoying minus sign! - : column
x + dx - dy(on rowy + dx + dy)
Why is x - dy annoying? Because x - dy shifts left while x + dx shifts right, and x - dy can go negative (< 0).
Now define — the column of the leftmost corner ! Substitute into all four corners:
- (leftmost): column
x' + 0on rowy + dx - (topmost): column
x' + dyon rowy - (bottommost): column
x' + dxon rowy + dx + dy - (rightmost): column
x' + dx + dyon rowy + dy
Every single column offset from x' is now (0, dy, dx, and dx + dy)!
That means if we shift those four rows right by 0, dy, dx, and dx + dy respectively, all four corners slide straight onto bit position x'! Bit x' of the 4-way bitwise AND:
is 1 if and only if all 4 corners of the (dx, dy) tilted square starting at (x', y) are #! (And notice: when dy == 0, this formula simplifies right back to our Part 1 formula!)
Step 2: Pre-Shift Everything Once (0.5 µs) = Zero Shifts Inside the Solver!
Wait: shifting a 141-bit row across three uint64_t boundaries ((r0 >> sh) | (r1 << (64 - sh))) inside a triple loop over (dy, dx, y) (467,180 iterations!) would do millions of shifts.
Look at our equation again: the only thing ever shifted is an original grid row R[r] >> sh, for row r ∈ [0..140] and shift sh ∈ [0..140]! There are only (shift, row) combinations total — precomputing all of them up front takes 0.5 microseconds, leaving zero bit shifts inside the solver!
Step 3: Why Both x and y Bounds Checks Vanish Into Thin Air
“Hold on,” you should ask, “what stops a square near the right edge or bottom edge from reading garbage bits and counting fake out-of-bounds squares?”
Two self-zeroing properties handle 100% of bounds checking for free:
- Right-edge (
x) overflow self-destructs: Unsigned right-shift (>>) always fills upper vacated bits with0. For the rightmost corner , rowy + dywas shifted right bys = dx + dy, so bits141 - sand above are guaranteed0. Anyx'whose rightmost corner automaticallyANDs against0and turns into0! - Bottom-edge (
y) overflow self-destructs: When we allocate our shifted arrayW[shift][y], instead of stopping at row140, we pad rows141 .. 191with0s! Whenever a SIMD vector at the end of a loop overhangs past the last valid row (y + dx + dy >= 141),W[dx][y + dx + dy]simply reads from the zero-padded zone (0), andanything & 0 == 0! Noifchecks, no remainder loops, no tail masks.
Try it yourself in the interactive register inspector below! Pick any (dx, dy) shape (notice row y = 1 detects 2 tilted squares simultaneously in a single AND!), hover different rows y on the left grid, or hover individual bit columns b0..b11 on the right to see which 4 grid cells map to that exact bit:
Step 4: Transpose Memory to W[shift][y] so GCC Auto-Vectorizes Everything!
Memory order makes or breaks SIMD. Suppose we stored W[y][shift]. Then as our inner loop walks y = 0, 1, 2, ... for a fixed (dx, dy), W[y][dy] would jump by 141 × 8 = 1,128 bytes on every step — striding across 18 different cache lines!
Flip the two array dimensions to W[shift][y] so consecutive rows y = 0, 1, 2, ... sit side-by-side in memory:
// Pure, portable C++23 inner loop — zero intrinsics!
const uint64_t* __restrict p0 = &W0[0][dx];
const uint64_t* __restrict p1 = &W0[dy][0];
const uint64_t* __restrict p2 = &W0[dx][dx + dy];
const uint64_t* __restrict p3 = &W0[dx + dy][dy];
for (int y = 0; y < 141 - (dx + dy); ++y) {
total += std::popcount(p0[y] & p1[y] & p2[y] & p3[y]);
}Look at that for loop. Four contiguous pointers stepping +1 per iteration, no branches, std::popcount. When you compile those 6 lines of completely standard C++23 with -O3 -march=native, GCC 15.2 sees the unit-stride access pattern and automatically vectorizes it into 512-bit AVX-512 instructions — loading 8 y rows × 64 x' bits = 512 candidate squares per iteration!
Step 5: Multi-Width Shrinking (64-bit → 32-bit → 16-bit)
One more geometric gem makes the bit-planes even tighter. Let , and let . Look at how large x' and y can be for a given :
- Valid columns
x':0 <= x' < 141 - s = R - Valid rows
y:0 <= y < 141 - s = R
Both dimensions of the valid search box shrink to as squares get larger!
- When (): All active
x'bits fit inside0..63— Word 1 (64..127) and Word 2 (128..140) are 100% zero, so we skip them completely! - When (): Active
x'bits fit inside a 32-bituint32_t(D0[shift][y]) — now a single 512-bit register packs 16yrows at once instead of 8 (2×denser)! - When (): Active
x'bits fit inside a 16-bituint16_t(H0[shift][y]), and there are at most16validyrows total ( = one__m256iload — the inneryloop disappears completely!).
With zero intrinsics, this pure C++23 bit-plane solver runs in 121.1 microseconds — 55.9× faster than v1 and 13.6× faster than v3!
7. Stage 6: Hitting 37.5 µs on Zen 5 (~160 Squares per Clock Cycle)
Why stop at 121 µs when we can look at the assembly GCC generated, ask where the remaining cycles went, and hand-craft an AVX-512 kernel tailored to Zen 5?
Writing a straightforward explicit AVX-512 version first brought us from 121.1 µs down to 75.4 µs — and then suddenly hit a hard ceiling. Let’s look at the three hardware tricks (two easy, one profound) that took us all the way from 121 µs → 75.4 µs → 37.5 µs median (35.9 µs min).
1. Parsing All 20,161 ASCII Bytes in 120 Nanoseconds
In our portable solver, building bitmasks char-by-char (row[x] == '#') took several microseconds. AVX-512 BW has a dream instruction for ASCII grids: _mm512_cmpeq_epi8_mask.
In one single instruction, it loads 64 ASCII bytes, compares all 64 bytes in parallel against '#' (0x23), and hands back the result directly as a 64-bit integer bitmask! Each 141-byte row (64 + 64 + 13) takes just 3 instructions:
const __m512i v_hash = _mm512_set1_epi8('#');
const __m128i v_hash128 = _mm_set1_epi8('#');
for (int y = 0; y < 141; ++y) {
const char* p = data + y * stride;
uint64_t r0 = _cvtmask64_u64(_mm512_cmpeq_epi8_mask(_mm512_loadu_si512(p), v_hash));
uint64_t r1 = _cvtmask64_u64(_mm512_cmpeq_epi8_mask(_mm512_loadu_si512(p + 64), v_hash));
uint64_t r2 = _cvtmask16_u32(_mm_cmpeq_epi8_mask(
_mm_loadu_si128(reinterpret_cast<const __m128i*>(p + 128)), v_hash128)) & 0x1FFFULL;
// ...
}3 comparisons × 141 rows = 423 instructions. Timed in isolation over 5,000 runs, parsing all 20,161 bytes takes 0.12 microseconds (120 nanoseconds)!
2. Three-Input Truth Tables (vpternlogq) + Native VPOPCNTDQ
Normally, ANDing four registers a & b & c & d takes 3 instructions ((a & b) & (c & d)). AVX-512 includes _mm512_ternarylogic_epi64(x, c, d, imm8) (vpternlogq), which evaluates any boolean function of 3 512-bit inputs in 1 clock cycle by encoding the 8-row truth table into an 8-bit immediate byte imm8!
For X & C & D, only row 7 (111 in binary → bit 7 of the byte) outputs 1, while rows 0..6 output 0 — which is 0b10000000 = 0x80:
static inline __m512i and4(__m512i a, __m512i b, __m512i c, __m512i d) {
// 2 instructions total instead of 3: vpandq + vpternlogq(0x80)!
return _mm512_ternarylogic_epi64(_mm512_and_si512(a, b), c, d, 0x80);
}We feed that mask straight into Zen 5’s single-cycle 512-bit population count instruction, _mm512_popcnt_epi64(m) (vpopcntq), accumulating counts in vector registers and reducing horizontally only once at the end.
3. Breaking the 75 µs Wall: Why Our Kernel Was Starving for Memory
Even with 120 ns SIMD parsing, vpternlogq, and vpopcntq, our first AVX-512 solver stalled at 75.4 µs. Two lines of back-of-the-envelope math immediately exposed why:
- The
48 KBL1D Cache Thrash: OurW0[141][152]bit-plane table is171 KB—3.5×larger than Zen 5’s48 KBL1 data cache! When our outer loop helddyfixed and sweptdx = 1 .. 140 - dy, every singledystreamed across the entire171 KBtable, evicting L1D completely on everydy(140 × 180 KB ≈ 25.2 MBof L2 cache traffic)! At Zen 5’s sustained L2→L1 bandwidth (~350 GB/s),25.2 MB / 350 GB/s =72 microseconds— matching our measured75.4 µsalmost to the microsecond! - The 2-Load-Pipe Bottleneck:
Zen 5 has 4 512-bit vector ALU pipes, but only 2 × 512-bit memory load pipes per cycle. Doing 4 memory loads (
p0,p1,p2,p3) for every single(dy, dx)pair meant the 2 load pipes hit100%saturation at2 cycles/pairwhile half our ALU pipes sat idle waiting for data!
We smashed both walls simultaneously:
- Fix A — Outer
12 × 12L1D Cache Tiling (25.2 MB→3.1 MBL2 traffic): Instead of sweepingdxall the way across1..140, we partition the(dy, dx)triangle into12 × 12tiles. Inside one12 × 12tile (144pairs!), the kernel only ever touchesW0[0](1row),W0[dy..dy+11](12rows),W0[dx..dx+11](12rows), andW0[s..s+22](23rows) =48rows ×~0.96 KB=~46 KB <= 48 KBL1D cache! Every single read inside the tile now hits 4-cycle L1 cache! - Fix B — Inner
4 × 4Register Blocking +valignqSliding Carry (4.0→1.0load/pair!): Inside each L1 tile, our micro-kernel evaluates a4 × 4block (16(dy, dx)pairs at once!) at row chunky. Notice how neighboring pairs ask for overlapping 8-row windows shifted by+1, +2, +3elements ([y+0..y+7],[y+1..y+8],[y+2..y+9],[y+3..y+10]). Instead of reloading from memory 4 times — or even 2 times! — we keep the previous 8-row vectorlo([y..y+7]) alive in azmmregister from the previousyiteration, perform just 1 new loadhi([y+8..y+15]), and slide a window across(hi, lo)in registers via_mm512_alignr_epi64(hi, lo, 1 / 2 / 3)(valignq)!
Across all 16 pairs in the 4 × 4 block, memory traffic drops from 64 loads down to 16 loads — averaging 1.00 load per pair! Load pipes and ALU pipes balance cleanly, dropping total Part 1 + Part 2 runtime to 37.5 µs median / 35.9 µs min (~160–167 complete 4-corner squares tested per single CPU clock cycle!).
Switch between the three vectorized kernels in the live Zen 5 simulator below to watch the 48 KB L1D cache bar, L2 traffic, execution pipes, and valignq register carry respond in real time:
8. Bonus Plot Twist: Reading the 20 KB File Took 2.5× Longer Than Solving the Puzzle
Once your solver runs in 37.5 µs, something hilarious happens when you benchmark the whole program: reading the 20 KB input file (95.4 µs) takes 2.5× longer than testing 33 million squares!
Why did two innocent lines of idiomatic C++ take 95.4 µs to read 20,161 bytes that were already warm in the OS RAM cache?
// 95.4 µs — convenient, idiomatic, and secretly doing 3 slow things!
std::ifstream file("input");
const std::string data(std::istreambuf_iterator{file}, {});- Windows Text-Mode
\r\nTranslation: Withoutstd::ios::binary,std::ifstreamopens in text mode on Windows — inspecting every byte to translate\r\n(143bytes/row on disk) into\n(142bytes/row in memory). - Single-Character Iterator Overhead:
std::istreambuf_iteratorhas no idea how big the file is, so it pulls one character at a time out of the stream buffer. - Repeated Heap Reallocations: Because
std::stringdoesn’t know the final20,021-byte length up front, it repeatedly allocates bigger heap buffers andmemcpys the prefix over and over as it grows (15 → 30 → 60 → ... → 20,021bytes).
Opening the file in binary mode and reading all 20,161 bytes in one single OS call straight into a 64-byte-aligned stack buffer (ReadFile or _open + _read) cuts I/O in half to 44.2 µs — and ~42 µs of that is purely the Windows NTFS kernel + Defender minifilter cost of opening and closing a file handle (the actual 20 KB copy from the OS page cache takes ~2 µs!). Even better, finding the first \n via memchr(buf, '\n', 256) - buf + 1 automatically detects stride = 143 (\r\n) or stride = 142 (\n) with zero text-mode translation.
9. Six Lessons You Can Steal for Any High-Performance Code
You rarely need 512-bit assembly in everyday code, yet the exact progression that took Day 3 from 6,764 µs → 1,650 µs → 474 µs → 121 µs → 37.5 µs repeats almost verbatim in game engines, compilers, databases, and physics solvers:
- Exploit canonical uniqueness (
dx > 0, dy >= 0): Whenever you’re searching for symmetric shapes (triangles, squares, collisions, graph motifs), pick one canonical anchor (like the unique topmost vertex) so every match is visited at most once without hash sets or deduplication. - Never scan empty space if your data is sparse (
v1 → v3): At8.57%#density, collecting active items cut 91% of empty.checks and gave an effortless 4.1× win. - Fear
50/50branches inside hot loops (v3 → Stage 4): A predictable loop branch is nearly free; a coin-flipif (dx <= 0)costs ~15 cycles per mispredict. Push inequalities outside the loop with algebra so every iteration inside the loop does guaranteed-valid work. - Pack booleans into bits (
SWAR): Turning1 byte per booleaninto1 bit per booleanshrinks memory 8× (20 KB → 3.3 KB, locking it inside L1 cache) and unlocks hardwarePOPCNT,TZCNT(std::countr_zero), andBLSR(m &= m - 1). - Re-anchor coordinates so memory streams with unit stride (
Stage 5): Substituting , pre-shifting once, zero-padding the tail so out-of-bounds lanes self-zero, and transposing toW[shift][y]let 6 lines of pure standard C++23 auto-vectorize to121 µs(55.9×faster) with zero intrinsics. - Do napkin math against cache sizes and CPU ports (
Stage 6): When SIMD code plateaus, multiply your loop’s byte footprint against L1D cache size (32–48 KB) and count loads per iteration vs. load pipes (2/cycle). Tiling for L1 (12 × 12) and sliding windows in registers (valignq) turned an L2-starved kernel into~160complete squares per clock cycle.