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

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

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


当前回答

可以通过以下两种方式确定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、MacOS、Windows跨平台解决方案:

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

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

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

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

如果你可以使用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())"

你也可以使用Python!获取物理核数:

$ python -c "import psutil; print(psutil.cpu_count(logical=False))"
4

获取超线程核的数量:

$ python -c "import psutil; print(psutil.cpu_count(logical=True))"
8

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