typestar

Parallel iterators in Rust

par_iter is iter with a work-stealing thread pool behind it.

use rayon::prelude::*;

fn expensive(n: u64) -> u64 {
    (1..=n).map(|k| k % 7).sum()
}

fn main() {
    let inputs: Vec<u64> = (1..=2_000).collect();

    let serial: u64 = inputs.iter().map(|n| expensive(*n)).sum();
    let parallel: u64 = inputs.par_iter().map(|n| expensive(*n)).sum();

    println!("{serial} == {parallel}: {}", serial == parallel);
    println!("threads: {}", rayon::current_num_threads());
}

How it works

  1. Swapping iter for par_iter is often the whole change.
  2. Rayon sizes the pool to the machine and splits the work.
  3. The result is identical; only the order of work differs.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
392
Tokens
141
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 3 in Parallel iterators, step 1 of 9 in Data parallelism with rayon.

Next →