How to Get Number of CPU Cores in Rust

on Jul 30, 2024 under Rust

In Rust, you can get the number of logical cores on the machine using the num_cpus crate. This crate provides a way to query the system for the number of available CPU cores, which is useful for applications that need to optimize their concurrency strategies based on the hardware they’re running on.

Here’s how you can use the num_cpus crate:

Step 1: Add num_cpus to Your Cargo.toml

First, you need to add the num_cpus crate to your project’s dependencies. Edit your Cargo.toml file to include:

[dependencies]
num_cpus = "1.0"

Step 2: Use num_cpus in Your Code

Then, in your Rust code, use num_cpus::get() to get the number of logical cores:

fn main() {
    let num_cores = num_cpus::get();
    println!("Number of logical cores is: {}", num_cores);
}

This code will print the number of logical cores available on your system. It’s worth noting that num_cpus::get() returns the number of logical cores, which can be different from the number of physical cores, especially on CPUs with hyper-threading.

Understanding Physical vs Logical Cores

  • Physical Cores: The actual physical cores in the CPU.
  • Logical Cores: If the CPU uses technologies like hyper-threading, each physical core can have multiple logical cores.

Using the number of logical cores is typically what you want for optimizing concurrency, as it represents the total number of threads that can run simultaneously without context switching.

Built with  Svelte Starter Kit