There's now a crate to do this: https://crates.io/crates/num_cpus
Add this to your Cargo.toml
:
[dependencies]
num_cpus = "0.2"
Then in your source:
extern crate num_cpus;
let num = num_cpus::get();
Question
I want to spawn a certain number of tasks based on the cores that a machine has. Is there anything in Rust that can find the number of cores, or should I just run external commands and parse the output?
Solution
There's now a crate to do this: https://crates.io/crates/num_cpus
Add this to your Cargo.toml
:
[dependencies]
num_cpus = "0.2"
Then in your source:
extern crate num_cpus;
let num = num_cpus::get();
OTHER TIPS
You could use std::os::num_cpus
. Example:
fn main() {
println!("{}", std::os::num_cpus());
}
You can use std::thread::available_parallelism
as of Rust 1.59.0:
use std::thread::available_parallelism;
let default_parallelism_approx = available_parallelism().unwrap().get();
It returns 12 on my machine with a Ryzen 5 4600H which is quite consistent with the number of logical processors it has.
It is now possible to use:
std::os::num_cpus
pub fn num_cpus() -> uint
Version of Rust:
$ rustc --version
rustc 0.13.0-nightly (d91a015ab 2014-11-14 23:37:27 +0000)
Reference: