How To Quickly Find The Number Of CPU Cores

Sometimes you need to determine how many CPU cores a system has. This might be when you’re running make to use some or all of your CPU cores or some compression tools that take a CPU cores argument.

If you’re not trying to find this number in a script you can grep the contents of /proc/cpuinfo:

cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3
processor       : 4
processor       : 5
processor       : 6
processor       : 7

Or you could open top and press 1 which will list all your CPU cores individually:

top - 12:56:04 up  3:04,  1 user,  load average: 0.58, 0.41, 0.38
Tasks: 231 total,   1 running, 230 sleeping,   0 stopped,   0 zombie
%Cpu0  :  0.7 us,  0.0 sy,  0.0 ni, 99.3 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu1  :  0.7 us,  0.7 sy,  0.0 ni, 98.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu2  :  0.7 us,  1.3 sy,  0.0 ni, 98.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu3  :  6.5 us,  1.3 sy,  0.0 ni, 92.2 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu4  :  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu5  :  4.3 us,  4.9 sy,  0.0 ni, 90.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu6  :  0.7 us,  1.3 sy,  0.0 ni, 98.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
%Cpu7  :  0.7 us,  2.0 sy,  0.0 ni, 97.4 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
GiB Mem :     15.1 total,      8.3 free,      2.6 used,      4.2 buff/cache
GiB Swap:      0.2 total,      0.2 free,      0.0 used.     10.6 avail Mem

Both of these solutions are a difficult to use in a script. If you need that information in an automated way just use nproc. When you run nproc it will output the number of CPU cores and nothing else:

$ nproc
8

If you need to get CPU cores minus N cores pass the --ignore=N flag:

$ nproc --ignore=1
7

You don’t need to employ grep or any other text manipulation or math tools to get the number you need.