Article View: comp.arch
Article #14Re: Optimization by programmers
From: Dan Cross
Date: Wed, 07 Oct 2026 19:57
Date: Wed, 07 Oct 2026 19:57
160 lines
6671 bytes
6671 bytes
In article <11a5lqo$2v5bq$1@dont-email.me>,
Terje Mathisen <terje.mathisen@tmsw.no> wrote:
>Dan Cross wrote:
>> In article <11a3ofn$2ak3s$1@dont-email.me>,
>> Terje Mathisen <terje.mathisen@tmsw.no> wrote:
>>> Dan Cross wrote:
>>>> In article <86h5j5pky9.fsf@linuxsc.com>,
>>>> Tim Rentsch <tr.17687@z991.linuxsc.com> wrote:
>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>
>>>>>> Tim Rentsch wrote:
>>>>>>
>>>>>>> Terje Mathisen <terje.mathisen@tmsw.no> writes:
>>>>>>>
>>>>>>>> Tim Rentsch wrote:
>>>>> [...]
>>>>>>>>> I favor a type equivalent to size_t for use as array index variables.
>>>>>>>>
>>>>>>>> In Rust, the only acceptable array index is of type "usize", which is
>>>>>>>> effectively the same as u64 on most platforms these days, but does not
>>>>>>>> need to be so: On a 32-bit target, it would be the same as u32.
>>>>>>>>
>>>>>>>> So effectively very similar to size_t.
>>>>>>>
>>>>>>> Maybe that limitation works okay in Rust. In C sometimes it's
>>>>>>> important to allow a signed value for indexing. Probably 99% of
>>>>>>> the time size_t is good, but not always.
>>>>>>
>>>>>> The fact that array indices are unsigned is one of the more crucial
>>>>>> underpinnings of Rust safety. Even more importantly, all such indices
>>>>>> are verified against the actual array upper boundary. [...]
>>>>>
>>>>> It's nice that array index values are checked against the array
>>>>> bounds.
>>>>
>>>> Terje was actually incorrect here; bounds checks are added in
>>>> debug mode, but are (usually) removed in optimized builds.
>>>
>>> That's what I assumed, except I check my assumptions by godbolt'ing my
>>> code, using -O -C "target_cpu=native" to get a bleeding edge optimized
>>> build, and that's where I saw a loop which started with
>>>
>>> while pos+7 < input.len() {
>>> ... here a bunch of accesses to input[p], input[p+1]...input[p+6]
>>> }
>>>
>>> Every one of those secodnary accesses were very obviously tested against
>>> the input length (stored in a register for the duration)
>>>
>>> I considered reporting this as a very clear performance bug!
>>
>> I wonder if what you saw was actually loop unrolling. I just
>> tried something similar, albeit with a very simple sum in the
>> loop body, and don't see a bunch of extraneous bounds checks.
>
>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.
>> 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.
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.
>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
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:
-->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.
- Dan C.
Technical Details
Message-ID:
<11a6870$41j$1@reader2.panix.com>Path:
mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mailReferences:
<1177fdi$26ea4$1@dont-email.me> <11a3ofn$2ak3s$1@dont-email.me> <11a5hd5$4qb$1@reader2.panix.com> <11a5lqo$2v5bq$1@dont-email.me>Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail From: cross@spitfire.i.gajendra.net (Dan Cross) Newsgroups: comp.arch Subject: Re: Optimization by programmers Date: Wed, 7 Oct 2026 19:57:20 -0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Message-ID: <11a6870$41j$1@reader2.panix.com> 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> Injection-Date: Wed, 7 Oct 2026 19:57:20 -0000 (UTC) Injection-Info: reader2.panix.com; posting-host="spitfire.i.gajendra.net:166.84.136.80"; logging-data="4147"; mail-complaints-to="abuse@panix.com" X-Newsreader: trn 4.0-test77 (Sep 1, 2010) Originator: cross@spitfire.i.gajendra.net (Dan Cross)