Detailed method for Linux to dynamically enable and to disable hyperthreading
- 2021-06-28 09:54:21
- OfStack
Preface
intel's hyperthreading technology allows one physical core to execute two threads in parallel, which in most cases improves the utilization of hardware resources and system performance.For cpu-intensive numeric programs, hyperthreading can cause overall program performance degradation.For this reason, it is recommended to turn off hyperthreading when executing OpenMP or MPI numeric programs.
The following is a script that dynamically turns hyperthreading on and off found on github.The principle is based on/sys/devices/system/cpu/cpuX/topology/thread_siblings_The list file finds the relationship between the logical cores and then edits the /sys/devices/system/cpu/cpuX/online file to dynamically open and close the hyperthreading technology.
#!/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
Remarks:
The script requires root privileges to execute; Enabled cpu information can be viewed through cat/proc/cpuinfo, which does not require root privileges; The lscpu command looks at the status of cpu (no root privilege is required): threads per core has a value of 2 in hyperthreaded state and 1 when disabled.
Reference resources
Disable / Enable HyperThreading cores on runtime linux
summary