I am running the following command to get the number of processors/cores in Linux:
cat /proc/cpuinfo | grep processor | wc -l
It works but it does not look elegant. How would you suggest improve it ?
I am running the following command to get the number of processors/cores in Linux:
cat /proc/cpuinfo | grep processor | wc -l
It works but it does not look elegant. How would you suggest improve it ?
This is for those who want to a portable way to count cpu cores on *bsd, *nix or solaris (haven't tested on aix and hp-ux but should work). It has always worked for me.
solaris
grep
&egrep
don't have-o
option sosed
is used instead.When someone asks for "the number of processors/cores" there are 2 answers being requested. The number of "processors" would be the physical number installed in sockets on the machine.
The number of "cores" would be physical cores. Hyperthreaded (virtual) cores would not be included (at least to my mind). As someone who writes a lot of programs with thread pools, you really need to know the count of physical cores vs cores/hyperthreads. That said, you can modify the following script to get the answers that you need.
The result on a machine with 2 model Xeon X5650 physical processors each with 6 physical cores that also support hyperthreading:
On a machine with 2 mdeol Xeon E5472 processors each with 4 physical cores that doesn't support hyperthreading
Another one-liner, without counting hyper-threaded cores:
I think the method you give is the most portable on Linux. Instead of spawning unnecessary
cat
andwc
processes, you can shorten it a bit:The most simplest tool comes with glibc and is called
getconf
:The
lscpu(1)
command provided by the util-linux project might also be useful: