Rayon Parallel Map
Map a slice in parallel with Rayon, turning a sequential iteration into work-stealing parallelism.
Code
use rayon::prelude::*;
/// Sum of squares, computed across all available worker threads.
pub fn sum_of_squares(values: &[i64]) -> i64 {
values.par_iter().map(|value| value.saturating_mul(*value)).sum()
}
/// Transform each element in place, preserving order in the result.
pub fn transform(value: &mut [i64], factor: i64) {
value.par_iter_mut().for_each(|slot| {
*slot = slot.checked_mul(factor).unwrap_or(*slot);
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn squares_match_sequential() {
let data: Vec<i64> = (1..=1000).collect();
let expected: i64 = data.iter().map(|v| v * v).sum();
assert_eq!(sum_of_squares(&data), expected);
}
}How the snippet works
Structurally, expect the functions sum_of_squares, transform and squares_match_sequential and nothing else.
Points of care
- External dependency:
rayon::prelude::andsuper::— install them before running the snippet.
Applying it
The main signature reads fn sum_of_squares(values: &[i64]) -> i64
sum_of_squares is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
let expected: i64 = data.iter().map(|v| v * v).sum();
values.par_iter().map(|value| value.saturating_mul(*value)).sum()
}
pub fn transform(value: &mut [i64], factor: i64) {
value.par_iter_mut().for_each(|slot| {
*slot = slot.checked_mul(factor).unwrap_or(*slot);
});
}
Interactive Tools for This Topic
FAQ
- What does this need from the package registry?
- These are real dependencies: `rayon::prelude::` and `super::`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.