如何从命令行获取 Linux 中的 CPU/内核数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6481005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to obtain the number of CPUs/cores in Linux from the command line?
提问by Richard
I have this script, but I do not know how to get the last element in the printout:
我有这个脚本,但我不知道如何获取打印输出中的最后一个元素:
cat /proc/cpuinfo | awk '/^processor/{print }'
The last element should be the number of CPUs, minus 1.
最后一个元素应该是 CPU 的数量,减去 1。
采纳答案by unbeli
grep -c ^processor /proc/cpuinfo
will count the number of lines starting with "processor" in /proc/cpuinfo
将计算以“processor”开头的行数 /proc/cpuinfo
For systems with hyper-threading, you can use
对于具有超线程的系统,您可以使用
grep ^cpu\scores /proc/cpuinfo | uniq | awk '{print }'
which should return (for example) 8
(whereas the command above would return 16
)
哪个应该返回(例如)8
(而上面的命令将返回16
)
回答by lunixbochs
This worked for me. tail -nX
allows you to grab only the last X lines.
这对我有用。tail -nX
允许您只抓取最后的 X 行。
cat /proc/cpuinfo | awk '/^processor/{print }' | tail -1
If you have hyperthreading, this should work for grabbing the number of physicalcores.
如果您有超线程,这应该可以用于获取物理内核的数量。
grep "^core id" /proc/cpuinfo | sort -u | wc -l
回答by foomiser
The following should give you the number of "real" cores on both a hyperthreaded and non-hyperthreaded system. At least it worked in all my tests.
以下应该为您提供超线程和非超线程系统上“真实”内核的数量。至少它在我所有的测试中都有效。
awk -F: '/^physical/ && !ID[] { P++; ID[]=1 }; /^cpu cores/ { CORES= }; END { print CORES*P }' /proc/cpuinfo
回答by uckelman
Processing the contents of /proc/cpuinfo
is needlessly baroque. Use nprocwhich is part of coreutils, so it should be available on most Linux installs.
处理内容/proc/cpuinfo
是不必要的巴洛克式。使用作为 coreutils 一部分的nproc,因此它应该在大多数 Linux 安装中可用。
Command nproc
prints the number of processing units available to the current process, which may be less than the number of online processors.
命令nproc
打印当前进程可用的处理单元数,可能小于在线处理器数。
To find the number of all installed cores/processors use nproc --all
要查找所有已安装内核/处理器的数量,请使用 nproc --all
On my 8-core machine:
在我的 8 核机器上:
$ nproc --all
8
回答by teambob
For the total number of physical cores:
对于物理内核总数:
grep '^core id' /proc/cpuinfo |sort -u|wc -l
On multiple-socket machines (or always), multiply the above result by the number of sockets:
在多插槽机器上(或总是),将上述结果乘以插槽数:
echo $(($(grep "^physical id" /proc/cpuinfo | awk '{print }' | sort -un | tail -1)+1))
@mklement0 has quite a nice answer below using lscpu. I have written a more succinct version in the comments
@mklement0 在下面使用 lscpu 有一个很好的答案。我在评论中写了一个更简洁的版本
回答by tim_yates
If you want to do this so it works on linux and OS X, you can do:
如果你想这样做,让它在 linux 和 OS X 上工作,你可以这样做:
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
回答by Chaim Geretz
Not my web page, but this command from http://www.ixbrian.com/blog/?p=64&cm_mc_uid=89402252817914508279022&cm_mc_sid_50200000=1450827902works nicely for me on centos. It will show actual cpus even when hyperthreading is enabled.
不是我的网页,而是来自http://www.ixbrian.com/blog/?p=64&cm_mc_uid=89402252817914508279022&cm_mc_sid_50200000=1450827902 的这个命令在centos上对我来说很好用。即使启用了超线程,它也会显示实际的 CPU。
cat /proc/cpuinfo | egrep "core id|physical id" | tr -d "\n" | sed s/physical/\\nphysical/g | grep -v ^$ | sort | uniq | wc -l
cat /proc/cpuinfo | egrep "core id|physical id" | tr -d "\n" | sed s/physical/\\nphysical/g | grep -v ^$ | sort | uniq | wc -l
回答by mklement0
Preface:
前言:
The problem with the
/proc/cpuinfo
-based answersis that they parse information that was meant for humanconsumption and thus lacks a stable format designed for machine parsing: the output format can differ across platforms and runtime conditions; usinglscpu -p
on Linux (andsysctl
on macOS) bypasses that problem.getconf _NPROCESSORS_ONLN
/getconf NPROCESSORS_ONLN
doesn't distinguish between logicaland physicalCPUs.
在这个问题
/proc/cpuinfo
为基础的答案是,他们这是意味着解析信息的人的消费,从而缺乏专为机解析一个稳定的格式:输出格式可以跨平台和运行时的条件不同; 使用lscpu -p
在Linux(和sysctl
在MacOS)绕过这个问题。getconf _NPROCESSORS_ONLN
/getconf NPROCESSORS_ONLN
不区分逻辑CPU和物理CPU。
Here's a sh
(POSIX-compliant) snippet that works on Linux and macOSfor determining the number of - online - logicalor physicalCPUs; see the comments for details.
这是一个sh
适用于Linux 和 macOS的(符合 POSIX 标准的)片段,用于确定在线逻辑或物理CPU 的数量;详情见评论。
Uses lscpu
for Linux, and sysctl
for macOS.
用途lscpu
用于Linux和sysctl
MacOS的。
Terminology note: CPUrefers to the smallest processing unit as seen by the OS. Non-hyper-threading cores each correspond to 1 CPU, whereas hyper-threading cores contain more than 1 (typically: 2) - logical - CPU.
Linux uses the following taxonomy[1], starting with the smallest unit:
CPU< core< socket< book< node
with each level comprising 1 or more instances of the next lower level.
术语说明:CPU是指操作系统所见的最小处理单元。非超线程内核每个对应 1 个 CPU,而超线程内核包含 1 个以上(通常:2 个)-逻辑-CPU。
Linux 使用以下分类法[1],从最小单元开始:
CPU<核心<套接字<书<节点
,每个级别包含下一个较低级别的 1 个或多个实例。
#!/bin/sh
# macOS: Use `sysctl -n hw.*cpu_max`, which returns the values of
# interest directly.
# CAVEAT: Using the "_max" key suffixes means that the *maximum*
# available number of CPUs is reported, whereas the
# current power-management mode could make *fewer* CPUs
# available; dropping the "_max" suffix would report the
# number of *currently* available ones; see [1] below.
#
# Linux: Parse output from `lscpu -p`, where each output line represents
# a distinct (logical) CPU.
# Note: Newer versions of `lscpu` support more flexible output
# formats, but we stick with the parseable legacy format
# generated by `-p` to support older distros, too.
# `-p` reports *online* CPUs only - i.e., on hot-pluggable
# systems, currently disabled (offline) CPUs are NOT
# reported.
# Number of LOGICAL CPUs (includes those reported by hyper-threading cores)
# Linux: Simply count the number of (non-comment) output lines from `lscpu -p`,
# which tells us the number of *logical* CPUs.
logicalCpuCount=$([ $(uname) = 'Darwin' ] &&
sysctl -n hw.logicalcpu_max ||
lscpu -p | egrep -v '^#' | wc -l)
# Number of PHYSICAL CPUs (cores).
# Linux: The 2nd column contains the core ID, with each core ID having 1 or
# - in the case of hyperthreading - more logical CPUs.
# Counting the *unique* cores across lines tells us the
# number of *physical* CPUs (cores).
physicalCpuCount=$([ $(uname) = 'Darwin' ] &&
sysctl -n hw.physicalcpu_max ||
lscpu -p | egrep -v '^#' | sort -u -t, -k 2,4 | wc -l)
# Print the values.
cat <<EOF
# of logical CPUs: $logicalCpuCount
# of physical CPUS: $physicalCpuCount
EOF
[1] macOS sysctl (3)
documentation
Note that BSD-derived systems other than macOS - e.g., FreeBSD - only support the hw.ncpu
key for sysctl
, which are deprecated on macOS; I'm unclear on which of the new keys hw.npu
corresponds to: hw.(logical|physical)cpu_[max]
.
请注意,除 macOS 以外的 BSD 派生系统(例如 FreeBSD)仅支持hw.ncpu
for 键sysctl
,该键在 macOS 上已弃用;我不清楚哪个新键hw.npu
对应于:hw.(logical|physical)cpu_[max]
。
Tip of the hat to @teambob for helping to correct the physical-CPU-count lscpu
command.
向@teambob 致敬,他帮助纠正了 physical-CPU-countlscpu
命令。
Caveat: lscpu -p
output does NOT include a "book" column (the man
page mentions "books" as an entity between socket and node in the taxonomic hierarchy). If "books" are in play on a given Linux system (does anybody know when and how?), the physical-CPU-count command may under-report (this is based on the assumption that lscpu
reports IDs that are non-unique across higher-level entities; e.g.: 2 different cores from 2 different sockets could have the same ID).
警告:lscpu -p
输出不包括“书”列(该man
页面提到“书”作为分类层次结构中套接字和节点之间的实体)。如果在给定的 Linux 系统上运行“书籍”(有人知道何时以及如何使用?),则 physical-CPU-count 命令可能会报告不足(这是基于以下假设:lscpu
报告的 ID在更高级别上是非唯一的)级实体;例如:来自 2 个不同插槽的 2 个不同内核可以具有相同的 ID)。
If you save the code above as, say, shell script cpus
, make it executable with chmod +x cpus
and place it in folder in your $PATH
, you'll see output such as the following:
如果您将上面的代码保存为 shell scriptcpus
,使其可执行chmod +x cpus
并将其放置在您的文件夹中$PATH
,您将看到如下输出:
$ cpus
logical 4
physical 4
[1] Xaekaisheds light on what a bookis: "a bookis a module that houses a circuit board with CPU sockets, RAM sockets, IO connections along the edge, and a hook for cooling system integration. They are used in IBM mainframes. Further info: http://ewh.ieee.org/soc/cpmt/presentations/cpmt0810a.pdf"
[1] Xaekai 阐明了书是什么:“书是一个模块,其中装有一块带有 CPU 插槽、RAM 插槽、边缘 IO 连接和用于冷却系统集成的挂钩的电路板。它们用于 IBM 大型机. 更多信息:http: //ewh.ieee.org/soc/cpmt/presentations/cpmt0810a.pdf"
回答by mshildt
The most portable solution I have found is the getconf
command:
我发现的最便携的解决方案是getconf
命令:
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
.
这适用于 Linux 和 Mac OS X。与其他一些方法相比,它的另一个好处是 getconf 已经存在很长时间了。我必须在其上进行开发的一些较旧的 Linux 机器没有nproc
或lscpu
命令可用,但它们有getconf
.
Editor's note: While the getconf
utilityis POSIX-mandated, the specific _NPROCESSORS_ONLN
and _NPROCESSORS_CONF
valuesare not.
That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _
.
编者注:虽然该getconf
实用程序是 POSIX-mandated,但具体_NPROCESSORS_ONLN
和_NPROCESSORS_CONF
值不是。也就是说,如前所述,它们可以在 Linux 平台和 macOS 上运行。在 FreeBSD/PC-BSD 上,您必须省略前导_
.
回答by Six
You can use one of the following methods to determine the number of physicalCPU cores.
您可以使用以下方法之一来确定物理CPU 内核的数量。
Count the number of unique core ids (roughly equivalent to
grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l
).awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo
Multiply the number of 'cores per socket' by the number of sockets.
lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'
Count the number of unique logical CPU's as used by the Linux kernel. The
-p
option generates output for easy parsing and is compatible with earlier versions oflscpu
.lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'
计算唯一核心 ID 的数量(大致相当于
grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l
)。awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo
将“每个插槽的核心数”乘以插槽数。
lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'
计算 Linux 内核使用的唯一逻辑 CPU 的数量。该
-p
选项生成输出以便于解析,并且与早期版本的lscpu
.lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'
Just to reiterate what others have said, there are a number of related properties.
只是重申其他人所说的话,有许多相关的属性。
To determine the number of processors available:
要确定可用的处理器数量:
getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo
To determine the number of processing units available (not necessarily the same as the number of cores). This is hyperthreading-aware.
确定可用的处理单元数量(不一定与内核数量相同)。这是超线程感知的。
nproc
I don't want to go too far down the rabbit-hole, but you can also determine the number of configured processors (as opposed to simply available/online processors) via getconf _NPROCESSORS_CONF
. To determine total number of CPU's (offline and online) you'd want to parse the output of lscpu -ap
.
我不想走得太远,但您也可以通过getconf _NPROCESSORS_CONF
. 要确定 CPU 的总数(离线和在线),您需要解析lscpu -ap
.