How Do You Find The Number of CPU Cores on Linux?

I have a script I want to make decisions based on the number of CPU execution cores in a machine. Of course, in order to make a decision the script first needs to find the number of cores in a machine. Problem is: how exactly do you do that? What an OS thinks is a CPU isn’t always a CPU, thanks to HyperThreading.

You could look at /proc/cpuinfo, but there isn’t anything there that tells you if a CPU core is real or a HyperThreading fake.

You could use dmidecode, but that’ll just count sockets, and you won’t know about the cores or HyperThreading.

In the end, you could just leave it to Intel to write sample code for you and call it a day. Save it as cpucount.cc and compile with “g++ -DLINUX -o cpucount cpucount.cc”. For my purposes I removed all the printf() statements except one that prints the number of physical cores. So all I get is:

$ ./cpucount
2

Seems too easy, right? Yeah, it doesn’t work right under VMware. But then again, under VMware you can just count the number of CPUs, ignoring the complexities of the physical world. 🙂

6 thoughts on “How Do You Find The Number of CPU Cores on Linux?”

  1. Bob, it’s easy without any Intel’s code. Just look at /proc/cpuinfo and you will see:
    physical id : 0
    core id : 1
    cpu cores : 2

    If you have two CPUs in cpuinfo with the same physical id and core id, than – hallo, hyperthreading! When you have all CPUs with different physical ids, than you have SMP, and when you have CPUs with one physical id and different core ids – you have one multicore CPU. And so on…

  2. Ah, look at that, ‘cat /proc/cpuinfo | egrep “physical id|core id”‘ does emit information I can use. For whatever reason I was having a tough time wrapping my head around that one. Thanks Andrey!

  3. I use this for the Number of Virtual Cores:
    lscpu | fgrep -i “CPU(s):” | head -1 | awk ‘{print $2;}’

    and this for the Physical Cores:
    cat /proc/cpuinfo | fgrep -i “cpu cores” | tail -1 | awk ‘{print $4;}’

    They seem to work on my machines

Comments are closed.