Linux количество ядер cpu

How to obtain the number of CPUs/cores in Linux from the command line?

Note that both of these will end up counting twice as many cores as actually exist if you’re on a system with hyperthreading (e.g, P4, or Core i7).

cat /proc/cpuinfo | awk ‘/^processor/‘ | tail -1 also will return the wrong number if the CPU numbers are 0-based.

The first line return 1 Core less then existing. Better cat /proc/cpuinfo | awk ‘/^processor/‘| wc -l

Processing the contents of /proc/cpuinfo is needlessly baroque. Use nproc which is part of coreutils, so it should be available on most Linux installs.

Command nproc prints the number of processing units available to the current process, which may be less than the number of online processors.

To find the number of all installed cores/processors use nproc —all

This doesn’t work with hyperthreading if I need the number of physical cores. Returns 8 on my quad core i7 box.

The most portable solution I have found is the getconf command:

getconf _NPROCESSORS_ONLN 

This works on both Linux and Mac OS X. Another benefit of this over some of the other approaches is that getconf has been around for a long time. Some of the older Linux machines I have to do development on don’t have the nproc or lscpu commands available, but they have getconf .

Editor’s note: While the getconf utility is POSIX-mandated, the specific _NPROCESSORS_ONLN and _NPROCESSORS_CONF values are not. That said, as stated, they work on Linux platforms as well as on macOS; on FreeBSD/PC-BSD, you must omit the leading _ .

This worked for me on Red Hat Entreprise Linux 5.4, Centos 6.5 & 7 and Mac OSX 10.9 (Mavericks). It seems this it the most portable, as lscpu is not installed by default on these systems. Thanks!

@CiroSantilli六四事件法轮功纳米比亚威视 From github.com/gstrauss/plasma/blob/master/plasma_sysconf.c it looks like I was wrong: it’s only optional. «sysconf _SC_NPROCESSORS_ONLN and _SC_NPROCESSORS_CONF are not required by standards, but are provided on numerous unix platforms and documented as optional by Open Group.»

@HaseebJadoon, you missed enclosing the getconf command in quotes /bin/sh -c ‘getconf _NPROCESSORS_ONLN’ . Though you asked a long time ago, just wanted to share my suggestion if it is helpful for you or someone else.

  • The problem with the /proc/cpuinfo -based answers is that they parse information that was meant for human consumption and thus lacks a stable format designed for machine parsing: the output format can differ across platforms and runtime conditions; using lscpu -p on Linux (and sysctl on macOS) bypasses that problem.
  • getconf _NPROCESSORS_ONLN / getconf NPROCESSORS_ONLN doesn’t distinguish between logical and physical CPUs.

Here’s a sh (POSIX-compliant) snippet that works on Linux and macOS for determining the number of — online — logical or physical CPUs; see the comments for details.

Читайте также:  Linux audio output to input

Uses lscpu for Linux, and sysctl for macOS.

Terminology note: CPU refers to the smallest processing unit as seen by the OS. Non-hyper-threading cores each correspond to 1 CPU, whereas hyper-threading cores contain more than 1 (typically: 2) — logical — CPU.
Linux uses the following taxonomy [1] , starting with the smallest unit:
CPU < core < socket < book < node
with each level comprising 1 or more instances of the next lower level.

#!/bin/sh # 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 - i.e., 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) # Print the values. cat  

Note that BSD-derived systems other than macOS - e.g., FreeBSD - only support the hw.ncpu key for sysctl , which are deprecated on macOS; I'm unclear on which of the new keys hw.npu corresponds to: hw.(logical|physical)cpu_[max] .

Tip of the hat to @teambob for helping to correct the physical-CPU-count lscpu command.

Caveat: lscpu -p output does NOT include a "book" column (the man page mentions "books" as an entity between socket and node in the taxonomic hierarchy). If "books" are in play on a given Linux system (does anybody know when and how?), the physical-CPU-count command may under-report (this is based on the assumption that lscpu reports IDs that are non-unique across higher-level entities; e.g.: 2 different cores from 2 different sockets could have the same ID).

If you save the code above as, say, shell script cpus , make it executable with chmod +x cpus and place it in folder in your $PATH , you'll see output such as the following:

$ cpus logical 4 physical 4 

Источник

How to know number of cores of a system in Linux?

I wanted to find out how many cores my system has, so I searched the same question in Google. I got some commands such as the lscpu command. When I tried this command, it gave me the following result:

$ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 4 On-line CPU(s) list: 0-3 Thread(s) per core: 1 Core(s) per socket: 4 Socket(s): 1 NUMA node(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 23 Stepping: 10 CPU MHz: 1998.000 BogoMIPS: 5302.48 Virtualization: VT-x L1d cache: 32K L1i cache: 32K L2 cache: 2048K NUMA node0 CPU(s): 0-3 

Which of those indicates cores of a Linux system?

Is there any other command to tell the number of cores, or am I assuming it is completely wrong?

Your image of text isn't very helpful. It can't be copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please edit your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors).

@สมหวังแนวหน้า kind of a nitpick, but the the grep arg should be processor , not precessor , correct? . Thanks for the help!

12 Answers 12

To get a complete picture you need to look at the number of threads per core, cores per socket and sockets. If you multiply these numbers you will get the number of CPUs on your system.

CPUs = Threads per core X cores per socket X sockets

CPUs are what you see when you run htop (these do not equate to physical CPUs).

Here is an example from a desktop machine:

$ lscpu | grep -E '^Thread|^Core|^Socket|^CPU\(' CPU(s): 8 Thread(s) per core: 2 Core(s) per socket: 4 Socket(s): 1 
$ lscpu | grep -E '^Thread|^Core|^Socket|^CPU\(' CPU(s): 32 Thread(s) per core: 2 Core(s) per socket: 8 Socket(s): 2 

The output of nproc corresponds to the CPU count from lscpu . For the desktop machine above this should match the 8 CPU(s) reported by lscpu :

The output of /proc/cpuinfo should match this information, for example on the desktop system above we can see there are 8 processors (CPUs) and 4 cores (core id 0-3):

$ grep -E 'processor|core id' /proc/cpuinfo processor : 0 core id : 0 processor : 1 core id : 0 processor : 2 core id : 1 processor : 3 core id : 1 processor : 4 core id : 2 processor : 5 core id : 2 processor : 6 core id : 3 processor : 7 core id : 3 

The cpu cores reported by /proc/cpuinfo corresponds to the Core(s) per socket reported by lscpu . For the desktop machine above this should match the 4 Core(s) per socket reported by lscpu:

$ grep -m 1 'cpu cores' /proc/cpuinfo cpu cores : 4 

To specifically answer your question you tell how many cores you have by multiplying the number of cores you have per socket by the number of sockets you have.

Cores = Cores per socket X Sockets

For the example systems above the desktop has 4 cores:

$ echo "Cores = $(( $(lscpu | awk '/^Socket\(s\)/< print $2 >') * $(lscpu | awk '/^Core\(s\) per socket/< print $4 >') ))" Cores = 4 
$ echo "Cores = $(( $(lscpu | awk '/^Socket\(s\)/< print $2 >') * $(lscpu | awk '/^Core\(s\) per socket/< print $4 >') ))" Cores = 16 

Another useful utility is dmidecode which outputs per socket information. In the case of the server system listed above we expect to see 8 cores per socket and 16 threads per socket:

$ sudo dmidecode -t 4 | grep -E 'Socket Designation|Count' Socket Designation: CPU1 Core Count: 8 Thread Count: 16 Socket Designation: CPU2 Core Count: 8 Thread Count: 16 

The lscpu command has a number of useful options that you may like to check out, for example:

$ lscpu --all --extended $ lscpu --all --parse=CPU,SOCKET,CORE | grep -v '^#' 

See man lscpu for details.

  • You need to be aware of sockets, cores and threads
  • You need to be careful of the term CPU as it means different things in different contexts

Источник

Как в Linux посмотреть количество ядер процессора

Если нужно посмотреть, сколько ядер в центральном процессоре на компьютере под управлением Linux, то на ум приходит Системный монитор (System Monitor) — аналог Диспетчера задач в Windows. Но если Диспетчера задач действительно показывает количество ядер и логических процессоров, то в System Monitor можно увидеть только количество логических процессоров.

С помощью System Monitor нельзя узнать количество реальных ядер процессора. На этом скриншоте 12 ядер, если знать, что на каждое ядро по 2 потока, то понятно, что реальных ядер 6.

Но ситуация становится более запутанной с новыми процессорами, в которых могут быть P-ядра и E-ядра.

Как в Linux посмотреть количество ядер процессора в командной строке

lscpu

Чтобы посмотреть количество ядер процессора в командной строке выполните следующую команду:

lscpu | grep -E '^Thread|^Core|^Socket|^CPU\('

В этом выводе количество реальных ядер содержится в строке «Core(s) per socket». В строке «CPU(s)» показано количество логических ядер. В строке «Thread(s) per core» выводится количество потоков на одно ядро.

inxi

Ещё один способ вывести информацию о центральном процессоре, подсказанный пользователем в комментарии, это утилита inxi.

Inxi — это утилита командной строки для вывода информации о системе. inxi показывает системное оборудование, ЦП, драйверы, Xorg, рабочий стол, ядро, версии gcc, процессы, использование ОЗУ и множество другой полезной информации.

Для установки inxi в Debian и производные дистрибутивы (Linux Mint, Kali Linux, Ubuntu) выполните команду:

В Arch Linux и производных дистрибутивах (BlackArch, Manjaro) начните с установки pikaur, как это показано в статье «Автоматическая установка и обновление пакетов AUR», а затем выполните команду:

Для вывода информации о центральном процессоре выполните команду:

Количество ядер содержится в строке «Info: 6-core model» в начале вывода.

CPU: Info: 6-core model: Intel Core i7-8750H bits: 64 type: MT MCP cache: L2: 1.5 MiB Speed (MHz): avg: 1333 min/max: 800/4100 cores: 1: 2200 2: 2200 3: 900 4: 900 5: 2200 6: 900 7: 900 8: 900 9: 2200 10: 900 11: 900 12: 900

Как в Linux посмотреть количество ядер процессора в графическом интерфейсе

Если вы предпочитаете графический интерфейс, то установите программу hardinfo.

В Debian и производных дистрибутивах (Linux Mint, Kali Linux, Ubuntu) это можно сделать командой:

sudo apt install hardinfo

В Arch Linux и производных дистрибутивах (BlackArch, Manjaro) начните с установки pikaur, как это показано в статье «Автоматическая установка и обновление пакетов AUR», а затем выполните команду:

Затем запустите программу HardInfo, это можно сделать через меню Пуск или в командной строке:

Информацию о количестве ядер вы можете найти в двух местах. Во-первых, на вкладке «Общая информация»:

Во-вторых на вкладке «Процессор».

Источник

Оцените статью
Adblock
detector