How to obtain the number of CPUs/cores in Linux from the command line?
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.
cat /proc/cpuinfo | awk '/^processor/{print $3}' | tail -1
or simply
grep -c ^processor /proc/cpuinfo
which will count number of lines starting with "processor" in /proc/cpuinfo
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
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 _
.
上一篇: 如何测试Bash文件中是否存在字符串?