Linux动态启用禁用超线程技术

41次阅读

共计 1562 个字符,预计需要花费 4 分钟才能阅读完成。

转载请注明文章出处: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.

参考

  1. Disable / Enable HyperThreading cores on runtime – linux

正文完
 0