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?
Determine number of cores using Rust
It would also be useful to have a standardized way for the number of threads to be configurable? A combination of environmental variables and an overriding command line option. –
Pinky
There's a crate to do this: num_cpus.
References:
Add this to your Cargo.toml
:
[dependencies]
num_cpus = "1.0"
Then in your source:
extern crate num_cpus;
let num = num_cpus::get();
And if you want the number of physical cores:
num_cpus::get_physical()
–
Safranine 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.
You could use std::os::num_cpus
. Example:
fn main() {
println!("{}", std::os::num_cpus());
}
@Arjan: Oh, you are right.
default_sched_threads()
is public, however, and should be usable, more or less, for the OP purposes. –
Kirkendall std::os::num_cpus is now gone, as is default_sched_threads, so the questions is now unanswered. The answers were good when presented, it is Rust that has changed. –
Thence
docs.rs/num_cpus/1.4.0/num_cpus/index.html "Replaces the deprecated functionality of std::os::num_cpus" –
Dilator
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:
std::os::num_cpus is now gone, as is default_sched_threads, so the questions is now unanswered. The answers were good when presented, it is Rust that has changed. –
Thence
© 2022 - 2024 — McMap. All rights reserved.