🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #17

Re: Optimization by programmers

#17
From: Terje Mathisen
Date: Wed, 07 Oct 2026 20:31
162 lines
7442 bytes
Dan Cross wrote:
> In article <11a5lqo$2v5bq$1@dont-email.me>,
> Terje Mathisen  <terje.mathisen@tmsw.no> wrote:
>> Not unrolling, the code is here:
>>
>> https://godbolt.org/z/YnY5G1K49
>>
>> The interesting part starts at line 28/29 .LBB0_02 in the asm window
>> where you can see (starting at line 37) a bunch of cmp r8,rsi / jae
>> <panic> sequences.
> 
> So you're not actually indexing into an _array_ here, but rather
> into a _slice_, which is always bounds-checked in safe Rust
> code.

My old asm/C brain _knows_ that a slice of something with a known 
address and total length is effectively the same thing as an unmutable 
array.

Even if it isn't, the fact that I start by verifying that the slice 
extends at least 7 bytes past the p index means that all of p, 
p+1,p+2...p+6 must be valid, right?

> 
>>> I do wonder, though, whether you'd get better object code using
>>> `input.iter().chunks(n)` or `.windows(n)`.
>>
>> I guess I can try this, I'm guessing chunks(7) will error out if less
>> than 7 elements are available?
> 
> But really what you want is to find all subsequences matching
> the regular expression , `mul([0-9]+,[0-9]+)`, and then extract
> the two numeric fields, multiple them, and sum the results.
> That's a reduction over a sequence of products, which is itself
> a reduction over a sequence of patches that yield pairs of
> integers.

Yes, doing it that way is easy!
> 
> I understand you want raw speed; a way to get that is to
> implement the DFA corresponding to that regexp by hand, and use
> something like Boyer Moore to handle the fixed part.

Collectively we've tried all sorts of stuff in order to come up with the 
absolute fastest solution, without having to use unsafe code.

> 
>> The code is from Advent of Code 2024 day 3,
>> https://github.com/TerjeWiigMathisen/aoc/tree/master/2024/day03
> 
> Oh, I don't do Advent of Code, but looking briefly at the
> problem description I don't see why you couldn't use `&str` to

I typically pass the input to my process(inp:&str) function that way, 
but by turning it into a naked byte array (slice?), indexing is better 
defined with no need to iterate over a potential UTF8 sequence (even 
though we know there won't be any).

> represent the input data.  Nothing says it's not UTF-8, and from
> what I understand, the guy who runs it usually isn't a jerk
> about that kind of thing.  I haven't tried to benchmark your
> code against, e.g., this:

What you implement here is just Part1: After solving that you get to 
read Part2 where you have to also detect "do()" and "don't()" sequences, 
so that the multiplication result only adds to the part2 result if we're 
not following a don't().
> 
> -->BEGIN<---
> pub fn next(mut s: &str) -> Option<(i32, &str)> {
>      while !s.is_empty() {
>          let pos = s.find("mul(")?;
>          let (_, rest) = s.split_at(pos + 4);
>          s = rest;
>          let comma = s.find(|c: char| !c.is_ascii_digit())?;
>          let (adigits, rest) = s.split_at(comma);
>          let Some(rest) = rest.strip_prefix(",") else {
>              s = rest;
>              continue;
>          };
>          let a = adigits.parse::<i32>().ok()?;
>          let rparen = rest.find(|c: char| !c.is_ascii_digit())?;
>          let (bdigits, rest) = rest.split_at(rparen);
>          let Some(rest) = rest.strip_prefix(")") else {
>              s = rest;
>              continue;
>          };
>          let b = bdigits.parse::<i32>().ok()?;
>          return Some((a * b, rest));
>      }
>      None
> }
> 
> #[cfg(test)]
> mod tests {
>      use super::*;
> 
>      #[test]
>      fn invalids() {
>          assert_eq!(next("aaa"), None);
>          assert_eq!(next(""), None);
>          assert_eq!(next("mul(3,5"), None);
>          assert_eq!(next("mul(3, 5"), None);
>          assert_eq!(next("mul(3,"), None);
>          assert_eq!(next("mul(3"), None);
>          assert_eq!(next("mul("), None);
>      }
> 
>      #[test]
>      fn aproduct() {
>          let s = "abmul[1,2]mul(3,5)a";
>          assert_eq!(next(s), Some((15, "a")));
>      }
> 
>      #[test]
>      fn mproducts() {
>          let s = "mul(1,2)mul(3,4)";
>          let aopt = next(s);
>          assert_eq!(aopt, Some((2, "mul(3,4)")));
>          let (a, s) = aopt.unwrap();
>          let bopt = next(s);
>          assert_eq!(bopt, Some((12, "")));
>          let (b, s) = bopt.unwrap();
>          assert_eq!(next(s), None);
>          assert_eq!(a * b, 24);
>      }
> }
> --->END<---
> 
> I suspect yours may be somewhat faster, though this likely does
> more error checking.  YMMV.
> 

My guess is that your code (after adding the simultaneous scans for the 
do/don't markers) will take about twice as long (or more?) as the 7 us 
both my own and u/maneatingape (reddit handle of the guy with the 
fastest Rust solutions to all the 500+ puzzles) needs to deliver the result.

He is famous for solving every one of them in less than half a second:

His current total is 462 milliseconds for 524 stars.

I've managed to improve slightly on his code a few times, but more often 
  he is ahead of the best I've been able to come up with.

Collectively, the group discussing this on reddit have tried many 
different search approaches, including unaligned load of 4 bytes as a 
u32, then compare that directly against "mul(", "do()" and "don'" in a 
match statement. For me, this was slower in Rust, but a C programmer 
gained a us or two this way.

Setting up a combined Boyer-Moore would be doable:

If the fourth byte is '(', ')' or "'", check the preceeding bytes, if 
not a match use a pre-computed skip table (maybe even one for each 
initial match?) to increment the pointer. Hmmm... maybe I'll try this!

Terje

-- 
- <Terje.Mathisen at tmsw.no>
"almost all programming can be viewed as an exercise in caching"
Technical Details
Message-ID: <11a6a6h$37i1n$1@dont-email.me>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
References: <1177fdi$26ea4$1@dont-email.me> <11a3ofn$2ak3s$1@dont-email.me> <11a5hd5$4qb$1@reader2.panix.com> <11a5lqo$2v5bq$1@dont-email.me> <11a6870$41j$1@reader2.panix.com>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: Terje Mathisen <terje.mathisen@tmsw.no>
Newsgroups: comp.arch
Subject: Re: Optimization by programmers
Date: Wed, 7 Oct 2026 22:31:12 +0200
Organization: A noiseless patient Spider
Lines: 162
Message-ID: <11a6a6h$37i1n$1@dont-email.me>
References: <1177fdi$26ea4$1@dont-email.me> <11a3ofn$2ak3s$1@dont-email.me>
 <11a5hd5$4qb$1@reader2.panix.com> <11a5lqo$2v5bq$1@dont-email.me>
 <11a6870$41j$1@reader2.panix.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 07 Oct 2026 20:31:15 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="3393591"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX19eypNgz3PQznjJFaRVNK/N5ccqs6A+bxLb2MdO0WTWTA=="; posting-host="c17f588ef9b5adf5026e3d3006504c1f"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101
 Firefox/140.0 SeaMonkey/2.53.24
Cancel-Lock: sha1:TxPp6oLhMMnEZOIdpqPXRxHKCxA= sha256:DteXWEFna/ovzXNbjAQGhk/mjhUbPEIeaOkezZlY7A4=
	sha1:7r037yoPrzU6cepYkF3p3EDTogc= sha256:zC+QkCVebtx5a+eapF5PZTp3Q78EvLEeEyoLNEK4RvI=
In-Reply-To: <11a6870$41j$1@reader2.panix.com>