Created
February 12, 2018 14:45
-
-
Save bvdmitri/697e5d126fe1330b5dcf8493be045513 to your computer and use it in GitHub Desktop.
OSX CPU throttling script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/bash | |
function disable_throttling() { | |
echo "Disabling CPU throttling" | |
for pid in `pgrep cputhrottle`; do | |
kill "$pid" | |
done | |
} | |
if [[ "$UID" -ne 0 ]]; then | |
echo "Running as super-user" | |
sudo "$0" "$@" | |
exit 0 | |
fi | |
if [[ -z "$1" ]]; then | |
echo "You should specify application names" | |
echo "" | |
echo "Usage $0 <app1> [ <app2> .. ] <cpu>" | |
echo "<application> - string: name of any application (or 'disable' to stop CPU throttling for any application)" | |
echo "<cpu> - number: cpu percentage (0..400)" | |
exit 0 | |
fi | |
if [[ "$1" == "disable" ]]; then | |
disable_throttling | |
exit 0 | |
fi | |
applicationsArrayLength=$(($#-1)) | |
applicationsArray=${@:1:$applicationsArrayLength} | |
cpuUsage=${@: -1} | |
echo "Throttling CPU usage for [$applicationsArray] ($cpuUsage %)" | |
declare -A cputhrottle_id_map | |
while true | |
do | |
for application in $applicationsArray; do | |
for pid in `pgrep -x "$application"`; do | |
if [ ! ${cputhrottle_id_map[$pid]+_} ]; then | |
echo "Found new process for $application (PID: $pid)" | |
cputhrottle "$pid" "$cpuUsage" &>/dev/null & | |
cputhrottle_id_map[$pid]="$application:$!" | |
echo "Throttling $application (PID: $pid) with cputhrottle (PID: $!)" | |
fi | |
# echo `ps -p 52848 -o comm=` | awk -F/ '{print $NF}' | |
done | |
done | |
echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" | |
for pid in "${!cputhrottle_id_map[@]}"; do | |
pid_application_name=`ps -p $pid -o comm= | awk -F/ '{print $NF}'` | |
pid_application_name_in_cputhrottle_map=`echo "${cputhrottle_id_map[$pid]}" | awk -F: '{print $1}'` | |
pid_cputhrottle=`echo "${cputhrottle_id_map[$pid]}" | awk -F: '{print $2}'` | |
pid_cputhrottle_name=`ps -p "$pid_cputhrottle" -o comm= | awk -F/ '{print $NF}'` | |
if [ ! -n "$(ps -p $pid -o pid=)" ] || [ "$pid_application_name" != "$pid_application_name_in_cputhrottle_map" ]; then | |
echo "Application $pid_application_name (PID: $pid) does not exist, clearing map from it" | |
unset cputhrottle_id_map[$pid] | |
if [ -n "$(ps -p $pid_cputhrottle -o pid=)" ] && [ "$pid_cputhrottle_name" == "cputhrottle" ]; then | |
echo "Killing cputhrottle process (PID: $pid_cputhrottle)" | |
kill "$pid_cputhrottle" | |
fi | |
fi | |
echo "$pid_application_name ($pid) - $pid_application_name_in_cputhrottle_map ($pid_cputhrottle)" | |
done | |
echo "=======================================================" | |
sleep 5 | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment