Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the number of CPUs/cores in Linux from the command line?

Tags:

linux

bash

cpu

core

I have this script, but I do not know how to get the last element in the printout:

cat /proc/cpuinfo | awk '/^processor/{print $3}'

The last element should be the number of CPUs, minus 1.

like image 693
Richard Avatar asked Jun 25 '11 22:06

Richard


People also ask

How do I check number of CPU cores?

Press Ctrl + Shift + Esc to open Task Manager. Select the Performance tab to see how many cores and logical processors your PC has.

How do I check RAM and CPU cores in Linux?

Open a terminal. 2. Use the cat command to display the data held in /proc/cpuinfo. This command will produce a lot of text, typically it will repeat the same information for the number of cores present in your CPU. A more concise means to get most of this information is via lscpu, a command that lists the CPU details.

What is CPU cores in Linux?

Here, the CPU(s) value indicates the number of logical cores, which is equal to 8 in our output. The number of logical cores is equal to “Thread(s) per core” × “Core(s) per socket” × “Socket(s)” and the number of physical cores on a machine equals “Core(s) per socket” × “Socket(s)”.

How many CPU cores does the server have Linux?

CPU(s): 4. Core(s) per socket: 4. CPU family: 6.


3 Answers

grep -c ^processor /proc/cpuinfo

will count the number of lines starting with "processor" in /proc/cpuinfo

For systems with hyper-threading, you can use

grep ^cpu\\scores /proc/cpuinfo | uniq |  awk '{print $4}'

which should return (for example) 8 (whereas the command above would return 16)

like image 52
unbeli Avatar answered Oct 09 '22 02:10

unbeli


Processing the contents of /proc/cpuinfo is needlessly baroque. Use nproc which is part of coreutils, so it should be available on most Linux installs.

Command nproc prints the number of processing units available to the current process, which may be less than the number of online processors.

To find the number of all installed cores/processors use nproc --all

On my 8-core machine:

$ nproc --all
8
like image 37
uckelman Avatar answered Oct 09 '22 00:10

uckelman


The most portable solution I have found is the getconf command:

getconf _NPROCESSORS_ONLN

This works on both Linux and Mac OS X. Another benefit of this over some of the other approaches is that getconf has been around for a long time. Some of the older Linux machines I have to do development on don't have the nproc or lscpu commands available, but they have getconf.

Editor's note: While the getconf utility is POSIX-mandated, the specific _NPROCESSORS_ONLN and _NPROCESSORS_CONF values are not. That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _.

like image 302
mshildt Avatar answered Oct 09 '22 00:10

mshildt