我有这个脚本,但我不知道如何获得打印输出中的最后一个元素:

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

最后一个元素应该是cpu数量减1。


当前回答

lscpu以人类可读的格式收集CPU架构信息/proc/cpuinfon:

# lscpu


Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    1
Core(s) per socket:    4
CPU socket(s):         2
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 15
Stepping:              7
CPU MHz:               1866.669
BogoMIPS:              3732.83
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              4096K
NUMA node0 CPU(s):     0-7

参见https://unix.stackexchange.com/questions/468766/understanding-output-of-lscpu。

其他回答

可以通过以下两种方式确定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 of lscpu. lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'


重申一下其他人所说的,有一些相关的属性。

要确定可用的处理器数量:

getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo

确定可用的处理单元数量(不一定与内核数量相同)。这是超线程感知的。

nproc

我不想太深入,但是您还可以通过getconf _NPROCESSORS_CONF确定已配置处理器的数量(而不是简单的可用/在线处理器)。要确定CPU的总数(离线和在线),您需要解析lscpu -ap的输出。

如果你想这样做,让它在linux和OS X上工作,你可以这样做:

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

上述答案适用于大多数情况,但如果您处于docker容器环境中,并且容器受到CpusetCpus的限制,那么您实际上无法通过上述方法获得真正的cpu内核。

在这种情况下,你需要这样做来获得真正的cpu内核:

grep -c 'cpu[0-9]' /proc/stat

如果您只想计算物理内核,这个命令可以满足我的需要。

lscpu -e | tail -n +2 | tr -s " " | cut -d " " -f 4 | sort | uniq | wc -w

非常基本,但似乎是计算实际的物理内核,忽略了逻辑计数

Python 3还提供了一些简单的方法来获取它:

$ python3 -c "import os; print(os.cpu_count());"

4

$ python3 -c "import multiprocessing; print(multiprocessing.cpu_count())"

4