Search code examples
rustmulticorecpuid

How do I find out the number of CPU cores using cpuid?


I am interested in physical cores, not logical cores.

I am aware of https://crates.io/crates/num_cpus, but I want to get the number of cores using cpuid. I am mostly interested in a solution that works on Ubuntu, but cross-platform solutions are welcome.


Solution

  • I see mainly two ways for you to do this.

    You could use the higher level library cpuid. With this, it's as simple as cpuid::identify().unwrap().num_cores (of course, please do proper error handling). But since you know about the library num_cpus and still ask this question, I assume you don't want to use an external library.

    The second way to do this is do it all on your own. But this method of doing it is mostly unrelated to Rust as the main difficulty lies in understanding the CPUID instruction and what it returns. This is explained in this Q&A, for example. It's not trivial, so I won't repeat it here.

    The only Rust specific thing is how to actually execute that instruction in Rust. One way to do it is to use core::arch::x86_64::__cpudid_count. It's an unsafe function that returns the raw result (four registers). After calling it, you have to extract the information you want via bit shifting and masking as described in the Q&A I linked above. Consult core::arch for other architectures or more cpuid related functions.

    But again, doing this manually is not trivial, error prone and apparently hard to make work truly cross-CPU. So I would strongly recommend using a library like num_cpus in any real code.