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

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

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


当前回答

这很简单。只需使用这个命令:

lscpu

其他回答

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

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

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

可以通过以下两种方式确定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的输出。

这个线程中的大多数答案都与逻辑核心有关。

在Ubuntu 18上使用BaSH。x,我发现这可以很好地确定物理cpu的数量:

numcpu="$(lscpu | grep -i 'socket(s)' | awk '{print $(2)}')"

它应该可以在大多数Linux发行版上运行。

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。

如果你可以使用Python,那么numexpr模块有一个函数:

In [5]: import numexpr as ne

In [6]: ne.detect_number_of_cores()
Out[6]: 8

也:

In [7]: ne.ncores
Out[7]: 8

从命令提示符中查询该信息使用:

# runs whatever valid Python code given as a string with `-c` option
$ python -c "import numexpr as ne; print(ne.ncores)"
8

或者简单地说,可以从multiprocessing.cpu_count()函数中获得此信息

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

或者干脆使用os.cpu_count()

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