9

I'm using the Rayon library:

extern crate rayon;

const N: usize = 1_000_000_000;
const W: f64 = 1f64/(N as f64);

fn f(x: f64) -> f64 {
    4.0/(1.0+x*x)
}

fn main() { 
    use rayon::prelude::*;
    let sum : f64 = (0..N)
        .into_par_iter()
        .map(|i| f(W*((i as f64)+0.5)))
        .sum::<f64>();
    println!("pi = {}", W*sum);
}

I want to run this code using different number of threads: 1, 2, 3 and 4.

I have read the documentation about How many threads will Rayon spawn? which says:

By default, Rayon uses the same number of threads as the number of CPUs available. Note that on systems with hyperthreading enabled this equals the number of logical cores and not the physical ones.

If you want to alter the number of threads spawned, you can set the environmental variable RAYON_NUM_THREADS to the desired number of threads or use the ThreadPoolBuilder::build_global function method.

However, the steps are not clear for me. How can I do this on my Windows 10 PC?

Community
  • 1
  • 1
asyraaf azhar
  • 383
  • 4
  • 12
  • 2
    well you could do what it's written... https://docs.rs/rayon/1.2.1/rayon/struct.ThreadPoolBuilder.html – Stargateur Dec 06 '19 at 01:03
  • ohh.. got it. just need to include this `rayon::ThreadPoolBuilder::new().num_threads(22).build_global().unwrap();` . Thank you – asyraaf azhar Dec 06 '19 at 01:17

2 Answers2

16

Just include in fn main(). The num_threads accepts the number of threads.

rayon::ThreadPoolBuilder::new().num_threads(4).build_global().unwrap();

asyraaf azhar
  • 383
  • 4
  • 12
3

If you don't want to set a global, you can create a function called 'create_pool'. This helper function constructs a Rayon ThreadPool object from num_threads.

pub fn create_pool(num_threads: usize) -> Result<rayon::ThreadPool, YOURERRORENUM> {
   match rayon::ThreadPoolBuilder::new()
      .num_threads(num_threads)
      .build()
   {
      Err(e) => Err(e.into()),
      Ok(pool) => Ok(pool),
   }
}

Then call your code from inside this create_pool. This will limit all Rayon functions to the num_threads you set.

[...]
    create_pool(num_threads)?.install(|| {
       YOURCODE
     })?;
[...]

For more see https://towardsdatascience.com/nine-rules-for-writing-python-extensions-in-rust-d35ea3a4ec29

Carl
  • 183
  • 6