pub fn default_threads() -> usize {
let available = std::thread::available_parallelism().map_or(1, |n| n.get());
num_cpus::get_physical().clamp(1, available)
}
pub fn init(threads: Option<usize>) -> usize {
let from_env = std::env::var("RAYON_NUM_THREADS")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|&n| n > 0);
let threads = threads.or(from_env).unwrap_or_else(default_threads);
match rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
{
Ok(()) => threads,
Err(_) => rayon::current_num_threads(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_is_within_the_available_cpus() {
let available = std::thread::available_parallelism().map_or(1, |n| n.get());
let threads = default_threads();
assert!(
(1..=available).contains(&threads),
"{threads} of {available}"
);
}
}