This is a simple Rust example to get the number of CPUs in a computer.

Solution 1: Use num_cpus

num_cpus is a Rust library that allows you to count the number of CPUs on the current machine.

Here’s how you use it:

Step 1: Install it

In your Cargo.toml declare it as a dependency:

[dependencies]
num_cpus = "1.0"

Step 2: Write Code

In your code:

extern crate num_cpus;

// count logical cores this process could try to use
let num = num_cpus::get();

Full Example

Here is the full example

main.rs

extern crate num_cpus;

fn main() {
    println!("Logical CPUs: {}", num_cpus::get());
    println!("Physical CPUs: {}", num_cpus::get_physical());
}

Reference

Read more here.

Categorized in: