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

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

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


当前回答

cat /proc/cpuinfo | grep processor

这工作得很好。当我尝试第一个答案时,我得到了3个CPU的输出。我知道我在系统上有4个cpu,所以我只是为处理器做了一个grep,输出看起来像这样:

[root@theservername ~]# cat /proc/cpuinfo | grep processor
processor       : 0
processor       : 1
processor       : 2
processor       : 3

其他回答

不是我的网页,但是来自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

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

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())"
 dmidecode  | grep -i cpu | grep Version

给我

版本:Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz 版本:Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz

这是正确的插座数量-查找E5-2667告诉我每个插座有8个核心,所以乘以,最终在2个插座上有16个核心。

lscpu给了我20个cpu -这是完全不正确的-不知道为什么。(cat /proc/cpu也一样-结果是20。

对于物理核总数:

grep '^core id' /proc/cpuinfo |sort -u|wc -l

在多插座机器(或总是)上,将上面的结果乘以插座的数量:

echo $(($(grep "^physical id" /proc/cpuinfo | awk '{print $4}' | sort -un | tail -1)+1))

@mklement0使用lscpu给出了一个很好的答案。我在评论中写了一个更简洁的版本