Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement custom fold for ZipSlice #762

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions benches/bench1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,20 @@ fn zipdot_i32_zipslices(c: &mut Criterion) {
});
}

fn zipdot_i32_zipslices_fold(c: &mut Criterion) {
let xs = vec![2; 1024];
let ys = vec![2; 768];
let xs = black_box(xs);
let ys = black_box(ys);
// output is 3072
c.bench_function("zipdot i32 zipslices fold", move |b| {
b.iter(|| {
let sum = ZipSlices::new(&xs, &ys).fold(0i32, |acc, (&x, &y)| acc + (x * y));
sum
})
});
}

fn zipdot_f32_zipslices(c: &mut Criterion) {
let xs = vec![2f32; 1024];
let ys = vec![2f32; 768];
Expand Down Expand Up @@ -812,6 +826,7 @@ criterion_group!(
zipslices,
zipslices_mut,
zipdot_i32_zipslices,
zipdot_i32_zipslices_fold,
zipdot_f32_zipslices,
zip_checked_counted_loop,
zipdot_i32_checked_counted_loop,
Expand Down
15 changes: 15 additions & 0 deletions benches/extra/zipslices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,21 @@ where
let len = self.len - self.index;
(len, Some(len))
}

#[inline(always)]
fn fold<B, F>(mut self, acc: B, mut f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
let mut accum = acc;
for i in self.index..self.len {
unsafe {
accum = f(accum, (self.t.get_unchecked(i), self.u.get_unchecked(i)));
}
}
accum
}
}

impl<T, U> DoubleEndedIterator for ZipSlices<T, U>
Expand Down