linux 获取内核线程数,如何从命令行获取Linux中的CPU /内核数量?

前言:

基于/proc/cpuinfo的答案的问题是,它们parsing了供人类使用的信息,因此缺乏为机器分析devise的稳定格式 :输出格式可能因平台和运行时间条件而有所不同; 在Linux上使用lscpu -p (和OSX上的sysctl )可以绕过这个问题 。

getconf _NPROCESSORS_ONLN / getconf NPROCESSORS_ONLN不区分逻辑 CPU和物理 CPU。

这里有一个bash代码片断,它可以在Linux和macOS上运行,以确定在线 – 逻辑或物理 CPU的数量 ; 请参阅评论的细节。

Linux使用lscpu ,macOS使用sysctl 。

术语说明 : CPU指操作系统所见的最小处理单元。 非超线程核心每个对应1个CPU,而超线程核心包含多于1个(通常是2个)逻辑CPU。

Linux使用以下分类法,从最小单元开始: CPU < 核心 < 套接字 < 书 < 节点 ,每个级别包括下一个较低级别的一个或多个实例。

我的知识有些不稳定 – 如果我错了,请告诉我。 有没有人知道在这方面“书”是什么?

# 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 - ie, 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)

[1] macOS sysctl (3)文档

请注意,除macOS以外的BSD派生系统(例如FreeBSD)仅支持sysctl的hw.ncpu密钥,这在macOS上已弃用; 我不清楚哪个新密钥hw.npu对应于: hw.(logical|physical)cpu_[max] 。

帮助纠正物理CPU数量lscpu命令的帽子提示lscpu 。

注意 : lscpu -p输出不包括“book”列( man页提到“books”是分类层次结构中套接字和节点之间的实体)。 如果“books”在给定的Linux系统上运行( 是否有人知道何时以及如何? ),则可能会报告physical-CPU-count命令(这是基于lscpu报告非唯一跨 ID 更高级的实体 ;例如:来自2个不同套接字的2个不同的核心可以具有相同的ID)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值