What is hyper threading in linux

Hyper-threading

A great way to troll Ops is to bring up Hyper-threading. So let’s document the debate and situation.

Contents

History

Once upon a time, HT was a new feature which Linux did not support well, due to the similarities and differences between SMP and HT. For this reason the conventional wisdom has been to disable HT in the BIOS.

However that was over 10 years ago, HT is now well supported on Linux, and the question becomes one of suitability to a workload.

Security

A security issue was raised back in 2005 concerning HT. FreeBSD disabled HT in the kernel to mitigate the issue. The Linux kernel community did not. Interesting discussion in:

The original security disclosure is in:

Performance claims

HT is said to increase performance of multi-threaded code by doubling the number of threads executed in parallel. That claim is regularly contested though:

Drawbacks

HT is said to decrease performance of HPC-style compute-intensive workloads such as floating point calculations. Links above apply as well for this.

Current practice

  • Most clusters have a mix of HT enabled/disabled hosts. This is a defect.
  • Platform-specific documentation continues to say to disable HT during initial setup, but doesn’t explain why

Checking

sudo lshw -class cpu | grep config
cat /sys/devices/system/cpu/cpu0/topology/thread_siblings | grep -q ',00000001$' && echo DISABLED || echo ENABLED
#!/bin/bash CPUFILE=/proc/cpuinfo test -f $CPUFILE || exit 1 # get number of physical CPUs NUMPHY=`grep "physical id" $CPUFILE | sort -u | wc -l` # get number of logical CPUs NUMLOG=`grep "processor" $CPUFILE | wc -l` # get number of cores per physical NUMCORE=`grep "core id" $CPUFILE | sort -u | wc -l` # calculate number of logical cores per physical core let NUMHTS=$NUMLOG/$NUMPHY/$NUMCORE if [ $NUMHTS -gt 1 ] ; then echo "HT=ON ($NUMLOG logical / ($NUMPHY physical * $NUMCORE cores each) = $NUMHTS logical per core)" else echo "HT=OFF ($NUMLOG logical / ($NUMPHY physical * $NUMCORE cores each) = $NUMHTS logical per core)" fi

Potentially this Puppet Facter Fact could also be extended to report HT status:

Читайте также:  Install touch screen linux

See also

Источник

Влияние многоядерности и Hyper-Threading на производительность в Linux (Sabayon / Gentoo)

Введение

Предметом настоящей заметки будет исследование влияния наличия многоядерности и включения технологии Hyper-Threading на производительность двух трудоемких задач: архивирование и инсталляции пакетов в Linux дистрибутиве Sabayon.

Sabayon является основанном на Gentoo дистрибутивом, особенностью которого является наличие как своего собственного бинарного менеджера пакетов, так и стандартного для Gentoo — Portage. Основной режим работы Portage — сборка пакетов из исходных кодов (как правило исходники на языках С и С++), при этом сборка может занимать весьма много времени. Главным преимуществом сборки из исходников, является возможность тонкой настройки нужной функциональности программ (используя USE флаги) и возможность воспользо.

реклама

Предметом настоящей заметки будет исследование влияния наличия многоядерности и включения технологии Hyper-Threading на производительность двух трудоемких задач: архивирование и инсталляции пакетов в Linux дистрибутиве Sabayon.

Sabayon является основанном на Gentoo дистрибутивом, особенностью которого является наличие как своего собственного бинарного менеджера пакетов, так и стандартного для Gentoo — Portage. Основной режим работы Portage — сборка пакетов из исходных кодов (как правило исходники на языках С и С++), при этом сборка может занимать весьма много времени. Главным преимуществом сборки из исходников, является возможность тонкой настройки нужной функциональности программ (используя USE флаги) и возможность воспользоваться всеми оптимизациями которые может дать компилятор для установленного у пользователя процессора (все расширения SSE и учет особенностей архитектуры ЦП).

Железо:
Core i7 920 @ 3000 (150 x 20, Turbo Boost On)
GigaByte GA-EX58-UD5
DDR3 1200 7-7-7-16 1, 12Гб

Софт:
ОС: Sabayon 4.2, 64 бит, ядро 2.6.29
gcc 4.3.3

Для тестирования производилось архивирование рабочих проектов в домашней директории в которой содержались текстовые и бинарные файлы суммарным объемом 200Мб. Данным тестом моделируется оперативный бэкап.
Использовалась две программы компрессора: bzip2 и pbzip2.
bzip2 — стандартная утилита для сжатия данных, очень популярная в мире Unix (наряду с gzip). Работает она в один поток.
pbzip2 параллельная реализация того же алгоритма, предназначенная для SMP машин, использует в работе библиотеку libbz2 (т.е. часть bzip2). Результирующий файл полностью совместим с форматом bzip2.

Читайте также:  Making symbolic link linux

bzip2 и pbzip2 были обновлены до версии 1.0.5, скомпилированы одним и тем же компилятором.

Команды для запуска задач:

time tar --use-compress-program bzip2 -cpvf /media/backup/backup.bz2 /home/user/dev 
time tar --use-compress-program pbzip2 -cpvf /media/backup/backup.bz2 /home/user/dev

Производилось по 3 запуска каждой команды. С целью исключения влияния на замеры производительности жесткого диска первый запуск не учитывался. Затраченное время на втором и третьем усреднялось и использовалось как результат.
Отключение HT производилось в BIOS.

pbzip2
В первую очередь отмечу, громадное превосходство параллельной версии pbzip2. pbzip2 с HT-on быстрее стандартного однопоточного bzip2 почти в 6 раз. А включение HT дало компрессору pbzip2 увеличение производительности на 23%.

В качестве теста была использована инсталляция XULRunner (библиотека используемая в Mozilla Firefox) и Qt-Webkit (наиболее объемная часть библиотеки Qt) с помощью системы Portage. Так как используется Portage, то все выводы полученные в ходе исследования будут верны и для Gentoo. Обе библиотеки написаны на C и C++. Процесс инсталляции запускается утилитой emerge, при этом начинает отрабатывать Python скрипт, который: при необходимости скачивающий упакованный пакет, затем его распаковывает, настраивает с помощью autoconf, собирает, инсталлирует и в конце проверяет зависимости. Процесс сборки наиболее трудоемкий, но к счастью есть возможность его распараллелить.
Файл /etc/make.conf был изменен при тестировании с HT: MAKEOPTS=»-s -j8″, без HT: MAKEOPTS=»-s -j4″, и сборка в один поток MAKEOPTS=»-s -j1″. Параметр jчисло служит для утилиты make указанием на сколько потоков можно распараллелить процесс сборки (чисто после j задает количество потоков) .

Команды для запуска задач:

реклама

Источник

How to check if Intel Hyper-Threading is enabled in Linux

Hyper-Threading is an Intel’s simultaneous multithreading (SMT) technology that is designed to improve execution parallelism of x86 CPU processors. With Hyper-Threading enabled, each physical core is represented as two «logical processors», each of which can execute jobs concurrently while sharing resources of the physical core. When one logical processor is halted or interrupted, the other logical processor on the same core can steal resources from the stalled processor. Thus, Hyper-Threading is expected to improve overall CPU throughput, and is particularly useful for multi-threaded applications which involve a mix of CPU- and I/O-intensive workloads, such as video encoding, 3D-rendering, gaming, etc.

Читайте также:  Linux изменение владельца директории

If you would like to check whether or not Hyper-Threading is enabled on your Linux system, there are several ways to do it.

Method One: BIOS settings

Hyper-Threading is a CPU processor feature. Hence typically you need to use BIOS settings to check whether or not Hyper-Threading is enabled. BIOS menu varies across different systems, and Hyper-Threading setting is typically found under «Advanced», «Processors» or «Performance» related settings. For example, the Hyper-Threading control in Dell XPS 13 BIOS is shown below.

Method Two: lscpu

Suppose you do not have access to your system’s BIOS menu for some reason (e.g., due to remote access). In that case, you can leverage the lscpu command which shows information about your system’s CPU architecture. In particular, look for Thread(s) per core entry in its output. If this entry says «1», it means only one thread is available per core. Hence Hyper-Threading is disabled. If it says «2», it means Hyper-Threading is enabled.

Therefore, simply use the following command to check the status.

Method Three: /sys/devices/system/cpu/smt/active

Another way to check the status of Hyper-Threading from the command line is to access the pseudo file located at /sys/devices/system/cpu/smt/active . The content of this file will be 1 (or on ) if Hyper-Threading is enabled, and 0 (or off ) otherwise.

$ cat /sys/devices/system/cpu/smt/active

Method Four: dmidecode

You can also check if Hyper-Threading is enabled by using the dmidecode command-line tool. Run it with -t processor , and compare «Core Count» and «Thread Count» in the output. If these two counts are the same, it means Hyper-Threading is not enabled. If «Thread Count» is twice of «Core Count», it means Hyper-Threading is enabled.

$ sudo dmidecode -t processor | grep Count

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Источник

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