Skip to content

Commit 8461d0b

Browse files
committed
Amortize init
1 parent 7731670 commit 8461d0b

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

src/kmeans.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,17 @@ impl Kmeans {
6464
let total = hist.total_perceptual_weight;
6565

6666
// chunk size is a trade-off between parallelization and overhead
67-
hist.items.par_chunks_mut(256).for_each({
68-
let tls = &tls;
69-
move |batch| {
70-
let kmeans = tls.get_or(move || CacheLineAlign(RefCell::new(Self::new(len))));
71-
if let Ok(ref mut kmeans) = *kmeans.0.borrow_mut() {
67+
hist.items.par_chunks_mut(256).for_each_init(
68+
|| tls.get_or(move || CacheLineAlign(RefCell::new(Self::new(len)))),
69+
move |kmeans, batch| {
70+
let Ok(mut tls) = kmeans.0.try_borrow_mut() else {
71+
debug_assert!(false);
72+
return;
73+
};
74+
if let Ok(ref mut kmeans) = *tls {
7275
kmeans.iterate_batch(batch, &n, colors, adjust_weight);
7376
}
74-
}
75-
});
77+
});
7678

7779
let diff = tls.into_iter()
7880
.map(|c| c.0.into_inner())

src/rayoff.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,18 @@ impl<T> IntoIterator for ThreadLocal<T> {
3131
}
3232
}
3333

34-
pub(crate) trait FakeRayonIter: Sized {
35-
fn par_bridge(self) -> Self;
34+
pub(crate) trait FakeRayonIter: Sized + Iterator {
35+
fn par_bridge(self) -> Self { self }
36+
fn for_each_init<I, F, T>(self, init: I, mut cb: F) where I: FnOnce() -> T, F: FnMut(&mut T, Self::Item) {
37+
let mut tmp = init();
38+
for item in self {
39+
cb(&mut tmp, item);
40+
}
41+
}
3642
}
3743

3844

39-
impl<T> FakeRayonIter for T where Self: Sized {
40-
fn par_bridge(self) -> Self { self }
45+
impl<T: Iterator> FakeRayonIter for T where Self: Sized {
4146
}
4247

4348
pub(crate) trait FakeRayonIntoIter<T> {

0 commit comments

Comments
 (0)