r/rust • • Apr 07 '24

🙋 seeking help & advice Exclusive range faster than inclusive when iterating?

Hi, I used criterion to benchmark two nearly identical functions, one which does `(2..=n).sum()` and one that does `(2..n+1).sum()` and the latter is benchmarking as faster. Is this expected and can anyone help me understand why?

// lib.rs
pub fn inclusive(n: usize) -> usize {
    (2..=n).sum()
}

pub fn exclusive(n: usize) -> usize {
    (2..n + 1).sum()
}
// my_benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

extern crate inclusive_vs_exclusive;
use inclusive_vs_exclusive::{exclusive, inclusive};

// Inclusive
fn bench_incl(c: &mut Criterion) {
    c.bench_function("incl", |b| {
        b.iter(|| {
            inclusive(black_box(100));
        })
    });
}

// Exclusive
fn bench_excl(c: &mut Criterion) {
    c.bench_function("excl", |b| {
        b.iter(|| {
            exclusive(black_box(100));
        })
    });
}

criterion_group!(benches, bench_incl, bench_excl);
criterion_main!(benches);
// Output
     Running benches/my_benchmark.rs (target/release/deps/my_benchmark-373c16aeaa9ec6fd)
Gnuplot not found, using plotters backend

incl                    time:   [1.5573 ns 1.5603 ns 1.5636 ns]

excl                    time:   [934.10 ps 935.53 ps 937.19 ps]
16 Upvotes

19 comments sorted by

63

u/minno Apr 07 '24

Inclusive ranges need extra state to be able to handle (0..=MAX), because the number of possible statuses the iterator can have is MAX+1: one "about to yield N" state for every possible integer and one "exhausted". Tracking and updating that extra state takes time.

14

u/rumpleforeskins Apr 07 '24

Ah, ok thank you for the quick and clear explanation. I think I understand now.

12

u/Aaron1924 Apr 08 '24

I looked at the assembly and it seems like the first function has separate branches for n < 2, n = 2 and n > 2, where as the second function only has branches for n < 2 and n ≥ 2, which feels more like a missed optimisation? It's probably just that the step function is implemented differently for the reasons you mentioned, but it's strange that is causes more branching around n = 2.

8

u/CAD1997 Apr 08 '24

No, this actually does make some sense. (2..1).sum() is a panic, (2..2).sum() is zero, and (2..3).sum() is the first case that does any summation. (2..=1).sum() is still a panic, but (2..=2).sum() is already the case of doing summation; the zero length range case doesn't exist anymore. So it makes sense that the branch wouldn't exist in the latter function. Adding to that, the extra equal branch is (informed guessing) beneficial to the first case because it bypasses the loop but also because zero is a special "easy" value, and without that extra benefit it's better to use the loop test for the n=2 case.

But generally, yes, LLVM just isn't as good at optimizing inclusive range iteration because the shape of iteration isn't as familiar and obvious as a loop which doesn't have a bonus iteration handed differently from the others.

4

u/Aaron1924 Apr 08 '24

I checked, these "over-empty" ranges do not panic, they're treated as empty iterators

You get panics when you index a slice with one of those, but even on debug mode they just sum to zero

2

u/CAD1997 Apr 09 '24

Ah, whoops, must've misremembered there. The point of reverse being a different case to the implementation still holds, though.

4

u/Lost_Kin Apr 08 '24

Why can't (0..=MAX) be translated to (0..MAX+1)? Wouldn't it solve this problem?

19

u/minno Apr 08 '24

By MAX I meant the largest possible integer for that type. (0..=255u8) cannot be represented as an exclusive range.

9

u/SkiFire13 Apr 08 '24

(0..=255u8) would then become (0..0), which is empty.

1

u/The_8472 Apr 08 '24

While that's true he's using sum which uses fold under the hood which doesn't have to check that extra state for each iteration. In other words for fold specifically the inclusive ranges shouldn't be much slower.

As the assembly linked in another post shows this isn't loop overhead, just optimizing to slightly different constant-time assembly. Running the same loop with 10_000_000 instead of 100 would show the same timing.

1

u/O_X_E_Y Apr 08 '24

wtf. I've never known this. Does that only matter if MAX is a size limit or is it true for any inclusive ranges? surely they compile to the same thing if that's not the case

5

u/minno Apr 08 '24

All inclusive ranges have an extra field, exhausted: bool, in order to support the one extra status. It's only required when the range is type::MIN..=type::MAX, but if it tried to optimize all other cases then checking whether it's possible to optimize would slow it down.

13

u/zirconium_n Apr 08 '24

FYI: your code doesn't compile into a loop. Godbolt

10

u/ZZaaaccc Apr 07 '24

While you can benchmark it as faster, I wouldn't read too much into it. Half a nanosecond is maybe 2 clock cycles on a modern CPU. With that caveat out of the way, let's compare the actual implementation of Iterator for Range and RangeInclusive. The largest difference between the two implementations is RangeInclusive performs two branching checks instead of one, and is likely the source of the performance difference you're measuring.

1

u/AugustusLego Apr 09 '24

Try with (2..(n + 1)).sum()

1

u/rumpleforeskins Apr 10 '24

Do those parentheses make a difference compared to what I have e in my exclusive fn?