aboutsummaryrefslogtreecommitdiff
path: root/temp_throttle.sh
blob: 9bdbcae8a3aab2d90784bd5af8d4e05b76e4188a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/bin/bash

# Usage: temp_throttle.sh max_temp
# USE CELCIUS TEMPERATURES.

cat << EOF
Author: Sepero (sepero 111 @ gmail . com)
 Remote Python developer and Linux administrator for hire.
URL: http://github.com/Sepero/temp-throttle/

EOF

# Additional Links
# http://github.com/Sepero/temp-throttle/
# http://seperohacker.blogspot.com/2012/10/linux-keep-your-cpu-cool-with-frequency.html

# License: GNU GPL 2.0

# Generic  function for printing an error and exiting.
function err_exit () {
	echo ""
	echo "Error: $@" 1>&2
	exit 128
}

if [ $# -ne 1 ]; then
	# If temperature wasn't given, then print a message and exit.
	echo "Please supply a maximum desired temperature in Celcius." 1>&2
	echo "For example:  ${0} 60" 1>&2
	exit 2
else
	#Set the first argument as the maximum desired temperature.
	MAX_TEMP=$1
fi

# The frequency will increase when low temperature is reached.
let LOW_TEMP=$MAX_TEMP-5

CORES=$(nproc) # Get number of CPU cores.
echo -e "Number of CPU cores detected: $CORES\n"

# Temperatures internally are calculated to the thousandth.
MAX_TEMP=${MAX_TEMP}000
LOW_TEMP=${LOW_TEMP}000

FREQ_FILE="/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies"
# FREQ_LIST is an array of available frequencies.
declare -a FREQ_LIST=($(cat $FREQ_FILE)) || err_exit "Could not determine available cpu frequencies. Missing file: $FREQ_FILE"
# CURRENT_FREQ will save the index of the currently used frequency in FREQ_LIST.
CURRENT_FREQ=1

# Set the maximum frequency for all cpu cores.
function set_freq {
	echo ${FREQ_LIST[$1]}
	for((i=0;i<$CORES;i++)); do
		echo ${FREQ_LIST[$1]} > /sys/devices/system/cpu/cpu$i/cpufreq/scaling_max_freq
	done
}

# Will reduce the frequency of cpus if possible.
function throttle {
	if [ $CURRENT_FREQ -ne $((${#FREQ_LIST[@]}-1)) ]; then
		let CURRENT_FREQ+=1
		echo -n "throttle "
		set_freq $CURRENT_FREQ
	fi
}

# Will increase the frequency of cpus if possible.
function unthrottle {
	if [ $CURRENT_FREQ -ne 0 ]; then
		let CURRENT_FREQ-=1
		echo -n "unthrottle "
		set_freq $CURRENT_FREQ
	fi
}

function get_temp {
	# Get the system temperature.
	# If one of these doesn't work, the try uncommenting another.
	
	TEMP=$(cat /sys/class/thermal/thermal_zone0/temp)
	#TEMP=$(cat /sys/class/hwmon/hwmon0/temp1_input) 
	#TEMP=$(cat /sys/class/hwmon/hwmon1/device/temp1_input)
}

# Mainloop
while true; do
	get_temp
	if   [ $TEMP -gt $MAX_TEMP ]; then # Throttle if too hot.
		throttle
	elif [ $TEMP -le $LOW_TEMP ]; then # Unthrottle if cool.
		unthrottle
	fi
	sleep 3
done