Rayon is a Rust crate for speeding up iterator-heavy work. It automatically uses multiple threads, often requiring only a parallel version of an iterator method. section 17.4
Common sequential iterator methods have parallel Rayon counterparts:
- Replace iter() with par_iter(). section 17.4
- Replace iter_mut() with par_iter_mut(), into_iter() with par_into_iter(), and chars() with par_chars(). section 17.4
- Import rayon::prelude::* to use these methods. section 17.4
Parallel vector update
Create a vector containing 2,000,000 zeros, then use par_iter_mut(), enumerate(), and for_each() to add each element's index plus one. The same computation can run faster on a machine with more available parallelism, but Rayon can also be slower for small or unsuitable workloads. section 17.4
use rayon::prelude::*; #1
fn main() {
let mut my_vec = vec![0; 2_000_000];
my_vec
.par_iter_mut()
.enumerate()
.for_each(|(index, number)| *number += index + 1); #2
}
Shows the minimal change from sequential mutation to Rayon-backed parallel mutation. section 17.4
