Filtering in parallel in Rust
filter, map and collect all have parallel versions that preserve order.
use rayon::prelude::*;
fn is_prime(n: u64) -> bool {
if n < 2 {
return false;
}
(2..=(n as f64).sqrt() as u64).all(|d| n % d != 0)
}
fn main() {
let primes: Vec<u64> = (2..50_000)
.into_par_iter()
.filter(|n| is_prime(*n))
.collect();
println!("{} primes", primes.len());
println!("last five {:?}", &primes[primes.len() - 5..]);
}
How it works
collectinto aVeckeeps the original ordering.- The closures must be
Send, so noRcinside. - Rayon only pays off once the work per item is real.
Keywords and builtins used here
Vecasboolf64fnifis_primeletmainreturnu64use
The run, in numbers
- Lines
- 18
- Characters to type
- 333
- Tokens
- 129
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 74 seconds.
Step 2 of 3 in Parallel iterators, step 2 of 9 in Data parallelism with rayon.