19 min read

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. 1. What the Puzzle Actually Asks (And How to Spot Any Square Without Trig)
  2. 2. My First Three Attempts (6.76 ms → 2.94 ms → 1.65 ms)
  3. 3. Why 1.65 ms Hits a Wall: A Friendly Tour Inside Your CPU
  4. 4. Stage 4: Bitboards, Exact Algebra & TZCNT Bit-Jumping (1,650 µs → 474 µs)
  5. 5. Stage 5A: Solving All of Part 1 in 1.30 µs with Two Bitwise ANDs
  6. 6. Stage 5B: The Big “Aha!” — Turning Tilted Squares into Shiftless Bit-Planes (474 µs → 121 µs in Pure C++23)
  7. 7. Stage 6: Hitting 37.5 µs on Zen 5 (~160 Squares per Clock Cycle)
  8. 8. Bonus Plot Twist: Reading the 20 KB File Took 2.5× Longer Than Solving the Puzzle
  9. 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 microseconds median (35.9 µs min) for Part 1 + Part 2 (180× faster than v1, 44× faster than v3 — faster than Windows NTFS takes just to open the input file!)
  • 1.30 microseconds median (1.20 µs min) for Part 1 alone (~769,000 full solves per second on a single core)
  • 121.1 microseconds median using 100% portable standard C++23 with zero SIMD intrinsics (55.9× faster than v1)

Here is the full optimization scoreboard before we start from square one:

Every stage verified bit-exact (Part 1 = 415, Part 2 = 2,553) on a single core of an AMD Ryzen 9 9950X3D (MinGW GCC 15.2.0, -std=c++23). Notice in Section II that the entire 37.5 µs solver finishes faster than a single Win32 ReadFile open/close syscall (44.2 µs).

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×1 up to 140×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 — the 415 flat squares plus 2,138 tilted 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 θ\theta, 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 P0=(x,y)P_0 = (x, y), and picking a second corner at P1=(rx,ry)P_1 = (rx, ry):

  1. To walk along the top-right edge from P0P_0 to P1P_1, you step right by dx = rx - x and down by dy = ry - y. (Remember: in grid coordinates, x grows to the right and y grows downward.)
  2. How do you turn 90∘90^\circ clockwise on graph paper without trigonometry? Swap the two step numbers and flip one sign! Stepping “right 3, down 1” (+dx, +dy) rotated 90∘90^\circ becomes “left 1, down 3” (-dy, +dx).
  3. Start back at P0=(x,y)P_0 = (x, y) and take that 90∘90^\circ-rotated step (-dy, +dx) to land on the third corner: P2=(x−dy,  y+dx)P_2 = (x - dy,\; y + dx)
  4. From P2P_2, take the original step (+dx, +dy) once more to close the bottom corner of the square: P3=(x−dy+dx,  y+dx+dy)P_3 = (x - dy + dx,\; y + dx + dy)

Let’s plug in real numbers on an 8 × 8 toy grid so there is zero mystery. Pick P0=(3,1)P_0 = (3, 1) and P1=(6,2)P_1 = (6, 2):

  • dx = 6 - 3 = 3, dy = 2 - 1 = 1.
  • P2=(3−1,  1+3)=(2,4)P_2 = (3 - 1,\; 1 + 3) = (2, 4).
  • P3=(2+3,  4+1)=(5,5)P_3 = (2 + 3,\; 4 + 1) = (5, 5).

Check the four sides: every single side moves (3, 1) or (-1, 3), so every side has length 32+12=10\sqrt{3^2 + 1^2} = \sqrt{10}, and their dot product is 3(−1)+1(3)=03(-1) + 1(3) = 0 (90∘90^\circ!). 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 4×3=124 \times 3 = 12 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):
    • P0=(x,y)P_0 = (x, y) (top-left)
    • P1=(x+dx,y)P_1 = (x + dx, y) (top-right)
    • P2=(x,y+dx)P_2 = (x, y + dx) (bottom-left)
    • P3=(x+dx,y+dx)P_3 = (x + dx, y + dx) (bottom-right) Every flat square has one unique top-left corner, so dy == 0, dx > 0 hits it once — and gives us Part 1!
  • Case B — Tilted square (dy > 0, dx > 0): Look at the y (row) coordinates of the 4 corners when both dx > 0 and dy > 0: y(P0)=y,y(P1)=y+dy>y,y(P2)=y+dx>y,y(P3)=y+dx+dy>yy(P_0) = y, \qquad y(P_1) = y + dy > y, \qquad y(P_2) = y + dx > y, \qquad y(P_3) = y + dx + dy > y P0P_0 has a strictly smaller y than all three other corners! Every tilted square has one unique highest corner on the grid, and from that highest corner, P1P_1 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):

C++
// 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,616 pairs — 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):

C++
// 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:

Interactive Square Search & Pruning Explorer. Hover any # tree and switch between v1 (4D Grid), v3 (Trees k≥i), and Bitboard + TZCNT to see red dx≤0 mispredicts and amber out-of-bounds checks vanish.

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 ConceptPlain-English AnalogyZen 5 Reality (Ryzen 9 9950X3D)
Clock CycleOne “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 PredictorA 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 HierarchyYour 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:

  1. Crime #1 — if (dx <= 0) is a literal 50/50 coin toss (725,000 random outcomes!): Because trees[k] is on a lower row than trees[i], its horizontal position rx is just as likely to fall left of x (dx <= 0) as right of x (dx > 0). Every time the CPU’s branch predictor guesses wrong on that coin flip, it flushes ~15 cycles of work down the drain!
  2. Crime #2 — valid(p2) and valid(p3) reject 67% of what’s left: Even when dx > 0, two-thirds of the remaining 725,000 pairs throw P2P_2 or P3P_3 off the left, right, or bottom edge of the 141 × 141 board! Out of 1,450,956 loop iterations, only ~241,000 (16.6% — 1 in 6!) are even geometrically allowed to form a square inside the grid!
  3. Crime #3 — Testing 1 square at a time: Checking occupied(p2) and occupied(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):

Text
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):

C++
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 x by 64 (x >> 6) to pick word 0, 1, or 2.
  • Take the remainder x % 64 (x & 63) to pick the bit inside that word:
C++
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 P0=(x,y)P_0 = (x, y) 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]?

  1. Leftmost corner P2=(x−dy,  y+dx)P_2 = (x - dy,\; y + dx) must have x−dy≥0x - dy \ge 0: x−(ry−y)≥0  ⟹  ry≤y+xx - (ry - y) \ge 0 \implies \mathbf{ry \le y + x} (Bonus: if x == 0, then ry <= y, which is impossible for dy >= 1 — so column 0 can never be the top corner of a tilted square!)
  2. Bottom corner P3=(rx−dy,  ry+dx)P_3 = (rx - dy,\; ry + dx) must have ry+dx≤140ry + dx \le 140: Since dx >= 1, we definitely need ry≤139ry \le 139. And substituting dx = rx - x: ry+(rx−x)≤140  ⟹  rx≤140+x−ryry + (rx - x) \le 140 \implies \mathbf{rx \le 140 + x - ry}
  3. Wait — what about P2P_2‘s y-bound (y+dx≤140y + dx \le 140) and P3P_3‘s x-bound (0≤rx−dy≤1400 \le rx - dy \le 140)? Check them!
    • Since ry > y and ry+dx≤140ry + dx \le 140, we automatically have y+dx<ry+dx≤140y + dx < ry + dx \le 140!
    • Since rx >= x + 1 and dy <= x (from rule #1!), we automatically have rx−dy≥(x+1)−x=1≥0rx - dy \ge (x + 1) - x = 1 \ge 0, and rx−dy<rx≤140rx - dy < rx \le 140!

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:

  1. std::countr_zero(m) (TZCNT — Trailing Zero Count): Counts how many 0 bits sit to the right of the lowest 1 bit — which is the exact column index of that 1 bit!
  2. m &= m - 1 (BLSR — Reset Lowest Set Bit): Clears that lowest 1 bit to 0 so 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):

Text
  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 d≥1d \ge 1 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:

Text
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 1 is 1 → column 1 has # on both top and bottom.
  • Bit 4 is 1 → column 4 (= 1 + 3!) also has # on both top and bottom! Together, columns 1 and 4 form a 3 × 3 square!
  • Bit 2 is 0, wait — what about columns 4 and 7 (= 4 + 3)? Both bit 4 and bit 7 are 1 in M — that’s a second 3 × 3 square 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!

Text
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 (1412)=9,870\binom{141}{2} = 9{,}870 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 P0=(x,y)P_0 = (x, y):

  • P0P_0: column x (on row y)
  • P1P_1: column x + dx (on row y + dy)
  • P2P_2: column x - dy (on row y + dx) ← annoying minus sign!
  • P3P_3: column x + dx - dy (on row y + 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 x′=x−dyx' = x - dy — the column of the leftmost corner P2P_2! Substitute x=x′+dyx = x' + dy into all four corners:

  1. P2P_2 (leftmost): column x' + 0 on row y + dx
  2. P0P_0 (topmost): column x' + dy on row y
  3. P3P_3 (bottommost): column x' + dx on row y + dx + dy
  4. P1P_1 (rightmost): column x' + dx + dy on row y + dy

Every single column offset from x' is now ≥0\ge 0 (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:

S(y,dx,dy)=(R[y+dx]≫0)  &  (R[y]≫dy)  &  (R[y+dx+dy]≫dx)  &  (R[y+dy]≫(dx+dy))S(y, dx, dy) = (R[y + dx] \gg 0) \;\mathbin{\&}\; (R[y] \gg dy) \;\mathbin{\&}\; (R[y + dx + dy] \gg dx) \;\mathbin{\&}\; (R[y + dy] \gg (dx + dy))

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!)

From 2D geometry to 512-bit SIMD in three moves: (1) re-anchor at x' = x - dy, (2) right-shift the four rows by 0, dy, dx, and dx+dy so all four corners align at bit x', and (3) transpose memory to W[shift][y] with zero-padded tail rows.

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 141×141=19,881141 \times 141 = \mathbf{19{,}881} (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:

  1. Right-edge (x) overflow self-destructs: Unsigned right-shift (>>) always fills upper vacated bits with 0. For the rightmost corner P1P_1, row y + dy was shifted right by s = dx + dy, so bits 141 - s and above are guaranteed 0. Any x' whose rightmost corner x′+dx+dy≥141x' + dx + dy \ge 141 automatically ANDs against 0 and turns into 0!
  2. Bottom-edge (y) overflow self-destructs: When we allocate our shifted array W[shift][y], instead of stopping at row 140, we pad rows 141 .. 191 with 0s! 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), and anything & 0 == 0! No if checks, 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:

Interactive Shifted Bit-Plane & Register Inspector. Pick a square slope (dx, dy), hover any row y on the 12×12 grid, or hover bit columns b0..b11 to watch 4 shifted rows align and detect multiple tilted squares in one bitwise AND.

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:

C++
// 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 s=dx+dys = dx + dy, and let R=141−sR = 141 - s. Look at how large x' and y can be for a given ss:

  • 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 R×RR \times R as squares get larger!

  • When s≥77s \ge 77 (R≤64R \le 64): All active x' bits fit inside 0..63 — Word 1 (64..127) and Word 2 (128..140) are 100% zero, so we skip them completely!
  • When s≥109s \ge 109 (R≤32R \le 32): Active x' bits fit inside a 32-bit uint32_t (D0[shift][y]) — now a single 512-bit register packs 16 y rows at once instead of 8 (2× denser)!
  • When s≥125s \ge 125 (R≤16R \le 16): Active x' bits fit inside a 16-bit uint16_t (H0[shift][y]), and there are at most 16 valid y rows total (16×16 bits=32 bytes16 \times 16\text{ bits} = 32\text{ bytes} = one __m256i load — the inner y loop 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).

The three pillars of our 37.5 µs Zen 5 kernel: (1) 120 ns SIMD ASCII mask parsing, (2) multi-width planes + 12×12 L1D cache tiling, and (3) 4×4 register blocking with valignq sliding-window carry.

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:

C++
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:

C++
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:

  1. The 48 KB L1D Cache Thrash: Our W0[141][152] bit-plane table is 171 KB — 3.5× larger than Zen 5’s 48 KB L1 data cache! When our outer loop held dy fixed and swept dx = 1 .. 140 - dy, every single dy streamed across the entire 171 KB table, evicting L1D completely on every dy (140 × 180 KB ≈ 25.2 MB of L2 cache traffic)! At Zen 5’s sustained L2→L1 bandwidth (~350 GB/s), 25.2 MB / 350 GB/s = 72 microseconds — matching our measured 75.4 µs almost to the microsecond!
  2. 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 hit 100% saturation at 2 cycles/pair while half our ALU pipes sat idle waiting for data!

We smashed both walls simultaneously:

  • Fix A — Outer 12 × 12 L1D Cache Tiling (25.2 MB → 3.1 MB L2 traffic): Instead of sweeping dx all the way across 1..140, we partition the (dy, dx) triangle into 12 × 12 tiles. Inside one 12 × 12 tile (144 pairs!), the kernel only ever touches W0[0] (1 row), W0[dy..dy+11] (12 rows), W0[dx..dx+11] (12 rows), and W0[s..s+22] (23 rows) = 48 rows × ~0.96 KB = ~46 KB <= 48 KB L1D cache! Every single read inside the tile now hits 4-cycle L1 cache!
  • Fix B — Inner 4 × 4 Register Blocking + valignq Sliding Carry (4.0 → 1.0 load/pair!): Inside each L1 tile, our micro-kernel evaluates a 4 × 4 block (16 (dy, dx) pairs at once!) at row chunk y. Notice how neighboring pairs ask for overlapping 8-row windows shifted by +1, +2, +3 elements ([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 vector lo ([y..y+7]) alive in a zmm register from the previous y iteration, perform just 1 new load hi ([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:

Interactive Zen 5 Cache Tiling & 4×4 Register-Carry Simulator. Compare Auto-Vectorized C++23 (121.1 µs), Naive AVX-512 (75.4 µs), and 12×12 L1-Tiled 4×4 Carry (37.5 µs).

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?

C++
// 95.4 µs — convenient, idiomatic, and secretly doing 3 slow things!
std::ifstream file("input");
const std::string data(std::istreambuf_iterator{file}, {});
  1. Windows Text-Mode \r\n Translation: Without std::ios::binary, std::ifstream opens in text mode on Windows — inspecting every byte to translate \r\n (143 bytes/row on disk) into \n (142 bytes/row in memory).
  2. Single-Character Iterator Overhead: std::istreambuf_iterator has no idea how big the file is, so it pulls one character at a time out of the stream buffer.
  3. Repeated Heap Reallocations: Because std::string doesn’t know the final 20,021-byte length up front, it repeatedly allocates bigger heap buffers and memcpys the prefix over and over as it grows (15 → 30 → 60 → ... → 20,021 bytes).

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:

  1. 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.
  2. Never scan empty space if your data is sparse (v1 → v3): At 8.57% # density, collecting active items cut 91% of empty . checks and gave an effortless 4.1× win.
  3. Fear 50/50 branches inside hot loops (v3 → Stage 4): A predictable loop branch is nearly free; a coin-flip if (dx <= 0) costs ~15 cycles per mispredict. Push inequalities outside the loop with algebra so every iteration inside the loop does guaranteed-valid work.
  4. Pack booleans into bits (SWAR): Turning 1 byte per boolean into 1 bit per boolean shrinks memory 8× (20 KB → 3.3 KB, locking it inside L1 cache) and unlocks hardware POPCNT, TZCNT (std::countr_zero), and BLSR (m &= m - 1).
  5. Re-anchor coordinates so memory streams with unit stride (Stage 5): Substituting x′=x−dyx' = x - dy, pre-shifting once, zero-padding the tail so out-of-bounds lanes self-zero, and transposing to W[shift][y] let 6 lines of pure standard C++23 auto-vectorize to 121 µs (55.9× faster) with zero intrinsics.
  6. 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 ~160 complete squares per clock cycle.