Number of cores

I recently needed to compute the number of cores on a system for a bash script.

My first naive approach was to look into /proc/cpuinfo and see if I could see a field with the proper count. I found one named siblings. I tried to glue a couple of commands to get what I needed:

grep siblings /proc/cpuinfo | head -1 | awk '{ print $3 }'

siblings was showing as much as I had cores, so I “cut” out the result to get the first line only and parsed the columns with awk.. Timing-wise it wasn't optimised at all:

real    0m0.029s
user    0m0.010s
sys     0m0.000s

Then I realized the siblings field wasn't present on all systems so I tried another approach.

I noticed The processor field showing up each time a core is there so I summed all line with a regex using grep. The timing is a bit better but I still felt it wasn't really a good answer for me:

grep -Ec "^processor\\s+:\\s[0-9]$" /proc/cpuinfo
real    0m0.021s
user    0m0.003s
sys     0m0.001s

Finally, I just asked on twitter if someone had something, and as a matter of fact, there is a GNU coreutils tool that does just that, called nproc:

nproc
real    0m0.002s
user    0m0.001s
sys     0m0.001s

Better 😄 !

Avatar
Julien Pericat
Linux Sysadmin, SysOps & DevOps friendly

Happily automating and putting things in containers.

Related