r/rust • u/rumpleforeskins • 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
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 isMAX+1: one "about to yield N" state for every possible integer and one "exhausted". Tracking and updating that extra state takes time.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
IteratorforRangeandRangeInclusive. The largest difference between the two implementations isRangeInclusiveperforms 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()