Determine number of cores using Rust
Asked Answered
W

4

42

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?

Winded answered 3/3, 2014 at 19:7 Comment(1)
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
G
53

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();
Grekin answered 21/5, 2015 at 1:16 Comment(1)
And if you want the number of physical cores: num_cpus::get_physical()Safranine
P
28

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.

Pampuch answered 4/9, 2022 at 11:59 Comment(0)
K
6

You could use std::os::num_cpus. Example:

fn main() {
    println!("{}", std::os::num_cpus());
}
Kirkendall answered 3/3, 2014 at 19:13 Comment(3)
@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
B
0

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

Bindery answered 16/11, 2014 at 11:41 Comment(1)
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.