Посмотреть сколько процессоров linux

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.
Читайте также:  Настроить сервер linux mysql apache

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.

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 

Источник

Информация о процессоре Linux

В зависимости от ваших потребностей о процессоре можно узнать различную информацию. Вам может понадобится производитель, модель, тактовая частота, количество ядер или потоков, конфигурация кэша, доступные расширения процессора (аппаратная виртуализация, AES, MMX, SSE) и так далее. В Linux существует уйма инструментов как командной строки так и с графическим интерфейсом которые показывают информацию об оборудовании и в том числе процессоре.

В этой статье собраны самые лучшие и удобные инструменты с помощью которых можно посмотреть характеристики процессора Linux. Среди них есть как консольные утилиты, так и графические.

Информация о процессоре Linux

1. /proc/cpuinfo

Простейший метод посмотреть характеристики процессора - открыть автоматически обновляемый системой файл /proc/cpuinfo. В этом файл показаны характеристики используемого процессора:

Здесь вы можете узнать количество ядер и потоков процессора, тактовую частоту, модель, доступные расширения процессора, и еще несколько других вещей.

2. cpufreq-info

Утилита cpufreq-info входит в набор утилит для управления частотой процессора cpufrequtils, и позволяет посмотреть частоту каждого из ядер процессора, максимальную и минимальную частоты на которых может работать процессор, а также политику управления cpufreq. Перед использованием утилиту надо установить:

sudo apt install cpufrequtils

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

3. cpuid

Консольная утилита cpuid показывает подробную информацию о процессоре используя набор функций CPUID. Выводится тип и семейство процессора, расширения, конфигурация кэша, TLB и информация про функции управления питанием. Для установки выполните:

4. dmidecode

Утилита dmidecode собирает подробную информацию об оборудовании системы на основе данных DMI в BIOS. Отображаемая информация включает производителя, версию процессора, доступные расширения, максимальную и минимальную скорость таймера, количество ядер, конфигурацию кэша L1/L2/L3 и т д. Здесь информация о процессоре Linux намного легче читается чем у предыдущей утилиты.

5. hardinfo

Hardinfo это графическая утилита которая позволяет получить информацию о процессоре и другом оборудовании в системе в графическом интерфейсе. Утилиту надо установить:

sudo apt install hardinfo

6. i7z

Утилита i7z - монитор параметров процессора в реальном времени для процессоров Intel Core i3, i5 и i7. Он отображает информацию по каждому ядру в реальном времени, такую как состояние TurboBoost, частота ядер, настройки управления питанием, температура и т д. У i7z есть консольный интерфейс основанный на Ncurses, а также графический на базе библиотек Qt.

7. inxi

Команда inxi - это bash скрипт, написанный для сбора информации о системе в удобном и понятном для человека виде. Он показывает модель процессора, размер кэша, скорость таймера и поддерживаемые дополнительные возможности процессора. Для установки используйте:

8. likwid-topology

Likwid (Like I Knew What I'm Doing) - это набор инструментов командной строки для измерения, настройки и отображения параметров оборудования компьютера. Информация о процессоре может быть выведена с помощью утилиты likwid-topology Она показывает модель и семейство процессора, ядра, потоки, кэш, NUMA. Установка:

9. lscpu

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

10. lshw

Команда lshw - универсальный инструмент для сбора данных об оборудовании. В отличии от других инструментов для lshw необходимы права суперпользователя так как утилита читает информацию из DMI в BIOS. Можно узнать общее количество ядер, и количество активных ядер. Но нет информации об кэше L1/L2/L3.

sudo lshw -class processor

11. lstopo

Утилита lstopo входит в пакет hwloc и визуализирует топологию системы. Сюда входит процессор, память, устройства ввода/вывода. Эта команда полезна для идентификации архитектуры процессора и топологии NUMA. Установка:

12. numactl

Первоначально разрабатываемая для настройки планировки NUMA и политик управления памятью в Linux numactl также позволяет посмотреть топологию NUMA:

13. x86info

x86info - инструмент командной строки для просмотра информации о процессорах архитектуры x86. Предоставляемая информация включает модель, количество ядер/потоков, скорость таймера, конфигурацию кэша, поддерживаемые флаги и т д. Установка в Ubuntu:

14. nproc

Утилита просто выводит количество доступных вычислительных потоков. Если процессор не поддерживает технологию HyperThreading, то будет выведено количество ядер:

15. hwinfo

Утилита hwinfo позволяет выводить информацию о различном оборудовании, в том числе и о процессоре. Программа отображает модель процессора, текущую частоту, поддерживаемые расширения. Наверное, это самый простой способ узнать частоту процессора Linux:

Выводы

В этой статье мы собрали самые популярные утилиты которые позволяют посмотреть процессор linux. Как видите, их действительно очень много. А какими программами пользуетесь вы? Мне нравится lscpu. Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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