Linux動態啓用/禁用超線程技術

轉載請註明文章出處:https://tlanyan.me/linux-enab...

intel的超線程技術能讓一個物理核上並行執行兩個線程,大多數情況下能提高硬件資源的利用率,增強系統性能。對於cpu密集型的數值程序,超線程技術可能會導致整體程序性能下降。鑑於此,執行OpenMP或者MPI數值程序時建議關閉超線程技術。

以下是github上找到的動態打開、關閉超線程技術的腳本。其原理是根據/sys/devices/system/cpu/cpuX/topology/thread_siblings_list文件找到邏輯核的關係,然後編輯/sys/devices/system/cpu/cpuX/online文件實現動態開啓和關閉超線程技術。

#!/bin/bash

HYPERTHREADING=1

function toggleHyperThreading() {
  for CPU in /sys/devices/system/cpu/cpu[0-9]*; do
      CPUID=`basename $CPU | cut -b4-`
      echo -en "CPU: $CPUID\t"
      [ -e $CPU/online ] && echo "1" > $CPU/online
      THREAD1=`cat $CPU/topology/thread_siblings_list | cut -f1 -d,`
      if [ $CPUID = $THREAD1 ]; then
          echo "-> enable"
          [ -e $CPU/online ] && echo "1" > $CPU/online
      else
        if [ "$HYPERTHREADING" -eq "0" ]; then echo "-> disabled"; else echo "-> enabled"; fi
          echo "$HYPERTHREADING" > $CPU/online
      fi
  done
}

function enabled() {
        echo -en "Enabling HyperThreading\n"
        HYPERTHREADING=1
        toggleHyperThreading
}

function disabled() {
        echo -en "Disabling HyperThreading\n"
        HYPERTHREADING=0
        toggleHyperThreading
}

#
ONLINE=$(cat /sys/devices/system/cpu/online)
OFFLINE=$(cat /sys/devices/system/cpu/offline)
echo "---------------------------------------------------"
echo -en "CPU's online: $ONLINE\t CPU's offline: $OFFLINE\n"
echo "---------------------------------------------------"
while true; do
    read -p "Type in e to enable or d disable hyperThreading or q to quit [e/d/q] ?" ed
    case $ed in
        [Ee]* ) enabled; break;;
        [Dd]* ) disabled;exit;;
        [Qq]* ) exit;;
        * ) echo "Please answer e for enable or d for disable hyperThreading.";;
    esac
done

備註:

  1. 腳本需root權限執行;
  2. 可以通過cat /proc/cpuinfo查看啓用的cpu信息,該命令無需root權限;
  3. lscpu命令可查看cpu的狀態(無需root權限):超線程狀態下threads per core數值爲2,禁用時爲1.

16bca80412f419e4?w=565&h=317&f=png&s=29271

參考

  1. Disable / Enable HyperThreading cores on runtime - linux
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章