Linux processors and cores

Linux: Find Number of CPU Cores Command

H ow do I find out the number of CPU cores available under HP x86_64 Linux serer running on RHEL / Debian Linux 6.x?

You can use the lscpu or nproc command to display the number of processing units available to the current process, which may be less than the number of online processors (please note that not all server supports hotplug a CPU on a running Linux system).[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

[/donotprint]

The proc file system is a pseudo-file system which is used as an interface to kernel data structures. It is commonly mounted at /proc. The /proc/cpuinfo file is nothing but a collection of CPU and system architecture dependent items, for each supported architecture a different list. Two common entries are processor which gives CPU number and bogomips; a system constant that is calculated during kernel initialization. SMP machines have information for each CPU.

nproc Example

The nproc command shows the number of processing units available:
# nproc
Sample outputs:

lscpu Command

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
# lscpu
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

/proc/cpuinfo

The /proc/cpuinfo and sysfs stores info about your CPU architecture ike number of CPUs, threads, cores, sockets, NUMA nodes, information about CPU caches, CPU family, model, bogoMIPS, yte order and much more:
# less /proc/cpuinfo

Here is a quick demo of lscpu and /proc/cpuinfo commands:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to Check Processor and CPU Details on Linux – Command Examples

Processor/Cpu details

The details about the processor that we shall be talking about include, number of cores, availability of hyper threading, architecture, cache size etc.

To find these details about the cpu on your system can be a bit difficult because the way different commands check them.

The commands that we are going to use include lscpu, /proc/cpuinfo and lstopo (hwloc).
These commands show detailed information about the cpu cores/processing units.

The examples following next would explain how to interpret the output of these commands.

1. Vendor and model of the processor

To find the vendor and model name of the processor, search the /proc/cpuinfo file with the grep command.

Its an Intel processor. Next find the model name that can be used to lookup the exact specifications online on Intel’s website.

Its a «Core 2 Quad Q8400» processor.

2. Architecture

The lscpu commands reports the architecture.

The architecture is x86_64 which is 64 bit.

3. Frequency

The frequency/speed of the processor is reported by both lscpu and /proc/cpuinfo.

The change of frequency can be seen by monitoring the output of /proc/cpuinfo using watch.

Run the above command in a terminal and while it is running, launch some cpu intensive task in parallel and the frequency would increase.

4. Number of cores

Each core on the processor is an actual independant cpu or processing unit. Multiple cores enable the processor to execute multiple program instructions in parallel, thereby increasing the processing speed.

The lscpu command indicates the «cores per socket».

So in this case the number of cores on the processor is 4.
The /proc/cpuinfo file also indicates the number of cores, but it can be bit tricky and confusing.

Simply counting the number of processors may give wrong numbers.

In case of hyper threaded processors, the number of processors that the operating system sees is twice the number of cores.

However /proc/cpuinfo has a field named ‘core id’ which is a unique id for each core in a single processor. Counting the core id would give a clear indication of the number of actual cores on the processor

Rare, but in case you are on a system that has multiple physical processors (yes, it means 2 or more processors fitted on the motherboard), then the results of /proc/cpuinfo would be different. In case of multiple processors, the ‘physical id’ would indicate multiple values.

If there are more than 1 physical ids, then there are multiple physical processors on the system. And you have to count the cores on each processor separately.

5. Hyper threading

Hyper threading is an Intel technology that allows individual cores to perform like 2 logical processing units. This, in a way increases the processing power of each core in a limited manner.

To check whether the processor has hyper-threading, 2 different values have to be compared. First is the number of actual cores, and second is the number of logical processing units.

If the number of cores is equal to the number of processing units as seen by the OS, then NO hyper threading. Otherwise if the number of processing units is greater/twice the number of cores, then YES hyper threading.

Take this example of a Core 2 Quad Q8400 processor

Number of processors as shown by /proc/cpuinfo is 4

Number of ‘cpu cores’ = 4 as well as ‘siblings’ = 4 and unique ‘core id’ = 4

Therefore total number of processing units = number of actual cores. So there is no hyper threading on this processor, and the same can be confirmed from the specs of the processor on Intel’s website.

Incase of hyper threading being present the output of /proc/cpuinfo or lscpu would be different.

Note the «Thread(s) per core: 2» which indicate that there are 2 threads per core, with a total of 4 cores. So the number of processing units seen by the OS is 8.

Now lets take a look at the output of /proc/cpuinfo.

The ‘cpu cores’ = 4 and siblings = 8 which means there are 4 cores and 2 hyperthreads per core. Number of processors as shown by /proc/cpuinfo would also be 8.

For the Core2Quad Q8400 processor, both dmidecode and /proc/cpuinfo show the hyperthreading flag enabled, inspite of hyper threading not being available on the processor.

Hwloc / lstopo

Hwloc (Portable hardware locality) is a small utility that reports the structure of the processor in a neat visual diagram. The diagram shows the number of cores, hyperthreads and cache size. A single diagram tells it all.

The above diagram clearly shows —

Total L2 Cache — 4096 KB — 4MB
Total Cores — 4
Processing unit per core — 1

Hyper-threaded processor
For a hyperthreaded processor, the hwloc output diagram could look like this

The diagram indicates

Total L3 Cache — 8MB
Total Cores — 4
Processing units per Core — 2 [hyper threading]

Conclusion

To learn more about commands for checking CPU information on Linux check this post:
9 Commands to Check CPU Information on Linux

If you have any feedback or questions let us know in the comments below.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

10 thoughts on “ How to Check Processor and CPU Details on Linux – Command Examples ”

If you are looking for physical CPU count /proc/cpuinfo is confusing . It gives the number of threads .

To get physical CPU count .

]# dmidecode -t 4 | egrep -i “Designation|Intel|core|thread”
Socket Designation: CPU1
Manufacturer: Intel
HTT (Multi-threading)
Version: Intel(R) Xeon(R) CPU L5640 @ 2.27GHz
Core Count: 6
Core Enabled: 6
Thread Count: 12
Socket Designation: CPU2
Manufacturer: Intel
HTT (Multi-threading)
Version: Intel(R) Xeon(R) CPU L5640 @ 2.27GHz
Core Count: 6
Core Enabled: 6
Thread Count: 12

The same server if i give

]# cat /proc/cpuinfo | egrep processor | wc -l
24

So its means i have a 24 threads system , so dont rely on cpuinfo .

Useless use of cat.

cat /proc/cpuinfo | grep processor

grep processor /proc/cpuinfo

In the last example you have hwloc as the command to run. You meant to have $ lstopo.

Источник

9 команд для проверки информации о CPU в Linux

Информация об аппаратном обеспечении CPU

Информация о CPU (Central Processing Unit. Центральный процессор) включает в себя подробные сведения о процессоре, такие как архитектура, название производителя, модель, количество ядер, скорость каждого ядра и т.д.

В linux существует довольно много команд для получения подробной информации о CPU.

В этой статье мы рассмотрим некоторые из часто встречающихся команд, которые можно использовать для получения подробной информации о CPU.

1. /proc/cpuinfo

Файл /proc/cpuinfo содержит подробную информацию об отдельных ядрах CPU.

Выведите его содержимое с помощью less или cat .

Каждый процессор или ядро перечислены отдельно, а различные подробности о скорости, размере кэша и названии модели включены в описание.

Чтобы подсчитать количество процессоров, используйте grep с wc

Количество процессоров, показанное в /proc/cpuinfo, может не соответствовать реальному количеству ядер процессора. Например, процессор с 2 ядрами и гиперпоточностью будет показан как процессор с 4 ядрами.

Чтобы получить фактическое количество ядер, проверьте идентификатор ядра на наличие уникальных значений

Соответственно, есть 4 разных идентификатора ядра. Это указывает на то, что существует 4 реальных ядра.

2. lscpu — отображение информации об архитектуре CPU

lscpu — это небольшая и быстрая команда, не требующая никаких опций. Она просто выводит информацию об аппаратном обеспечении CPU в удобном для пользователя формате.

3. hardinfo

Hardinfo — это gui инструмент на базе gtk, который генерирует отчеты о различных аппаратных компонентах. Но он также может запускаться из командной строки, в случае если отсутствует возможность отображения gui (Graphical User Interface — графический интерфейс пользователя).

Он создаст большой отчет о многих аппаратных частях, читая файлы из каталога /proc. Информация о CPU находится в начале отчета. Отчет также может быть записан в текстовый файл.

Hardinfo выполняет несколько эталонных тестов, занимающих несколько минут, прежде чем вывести отчет на экран.

4. lshw

Команда lshw может отобразить ограниченную информацию о CPU. lshw по умолчанию показывает информацию о различных аппаратных частях, а опция ‘ -class ‘ может быть использована для сбора информации о конкретной аппаратной части.

Производитель, модель и скорость процессора отображаются правильно. Однако из приведенного выше результата невозможно определить количество ядер в процессоре.

Чтобы узнать больше о команде lshw, ознакомьтесь с этой статьей:

5. nproc

Команда nproc просто выводит количество доступных вычислительных блоков. Обратите внимание, что количество вычислительных блоков не всегда совпадает с количеством ядер.

6. dmidecode

Команда dmidecode отображает некоторую информацию о CPU, которая включает в себя тип сокета, наименование производителя и различные флаги.

7. cpuid

Команда cpuid собирает информацию CPUID о процессорах Intel и AMD x86.

Программа может быть установлена с помощью apt на ubuntu

А вот пример вывода

8. inxi

Inxi — это скрипт, который использует другие программы для создания хорошо структурированного легко читаемого отчета о различных аппаратных компонентах системы. Ознакомьтесь с полным руководством по inxi.

Вывод соответствующей информации о CPU/процессоре

Чтобы узнать больше о команде inxi и ее использовании, ознакомьтесь с этой статьей:

9. Hwinfo

Команда hwinfo — это программа для получения информации об оборудовании, которая может быть использована для сбора подробных сведений о различных аппаратных компонентах в системе Linux.

Она также отображает информацию о процессоре. Вот быстрый пример:

Если не использовать опцию «—short», команда отобразит гораздо больше информации о каждом ядре CPU, например, архитектуру и характеристики процессора.

Чтобы более подробно изучить команду hwinfo, ознакомьтесь с этой статьей:

Заключение

Это были некоторые команды для проверки информации о CPU в системах на базе Linux, таких как Ubuntu, Fedora, Debian, CentOS и др.

Примеры других команд для проверки информации о CPU смотрите в этой статье:

Большинство команд обрабатываются с помощью интерфейса командной строки и выводятся в текстовом формате. Для GUI интерфейса используйте программу Hardinfo.

Она показывает подробности об аппаратном обеспечении различных компонентов в простом для использования GUI интерфейсе.

Если вы знаете какую-либо другую полезную команду, которая может отображать информацию о CPU, сообщите нам об этом в комментариях ниже

Если вы хотели бы узнать подробнее о формате обучения и программе, познакомиться с преподавателем курса — приглашаем на день открытых дверей онлайн. Регистрация здесь.

А если вам интересно развитие в этой сфере с нуля до pro, рекомендуем ознакомиться с учебной программой специализации.

Источник

How to check how many CPUs are there in Linux system

I am a new Linux user. How do you check how many CPUs are there in Linux system using the command line option?

Introduction: One can obtain the number of CPUs or cores in Linux from the command line. The /proc/cpuinfo file stores CPU and system architecture dependent items, for each supported architecture. You can view /proc/cpuinfo with the help of cat command or grep command/egrep command. This page shows how to use /proc/cpuinfo file and lscpu command to display number of processors on Linux.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements None
Est. reading time 3 minutes

How do you check how many CPUs are there in Linux system?

You can use one of the following command to find the number of physical CPU cores including all cores on Linux:

  1. lscpu command
  2. cat /proc/cpuinfo
  3. top or htop command
  4. nproc command
  5. hwinfo command
  6. dmidecode -t processor command
  7. getconf _NPROCESSORS_ONLN command

Let us see all commands and examples in details.

How to display information about the CPU on Linux

Just run the lscpu command:
$ lscpu
$ lscpu | egrep ‘Model name|Socket|Thread|NUMA|CPU\(s\)’
$ lscpu -p

The output clearly indicate that I have:

  1. CPU model/make: AMD Ryzen 7 1700 Eight-Core Processor
  2. Socket: Single (1)
  3. CPU Core: 8
  4. Thread per core: 2
  5. Total threads: 16 ( CPU core[8] * Thread per core [2])

Use /proc/cpuinfo to find out how many CPUs are there in Linux

Run top or htop command to obtain the number of CPUs/cores in Linux

Execute nproc print the number of CPUs available on Linux

Let us print the number of installed processors on your system i.e core count:
$ nproc —all
$ echo «Threads/core: $(nproc —all)»
Sample outputs:

How to probe for CPU/core on Linux using hwinfo command

$ hwinfo —cpu —short ## short info ##
$ hwinfo —cpu ## detailed info on CPUs ##

Linux display CPU core with getconf _NPROCESSORS_ONLN command

One can query Linux system configuration variables with getconf command:
$ getconf _NPROCESSORS_ONLN
$ echo «Number of CPU/cores online at $HOSTNAME: $(getconf _NPROCESSORS_ONLN)»
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

dmidecode -t processor command

You can use get BIOS and hardware information with dmidecode command (DMI table decoder) on Linux. To find out how many CPUs are there in Linux system, run:
$ sudo dmidecode -t 4
$ sudo dmidecode -t 4 | egrep -i ‘core (count|enabled)|thread count|Version’

Here is a quick video demo of lscpu and other commands:

Conclusion

You learned how to display information about the CPU architecture, core, threads, CPU version/model, vendor and other information using various Linux command line options.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Читайте также:  Windows make memory executable
Оцените статью