Advertisement
pushthis

changes CPU Freq based on cpu temp 😎

Jun 6th, 2025
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. #!/usr/bin/env bash
  2.  
  3. LOCKFILE=/tmp/thermal_governor.lock
  4.  
  5. # Try to acquire exclusive lock, fail if locked
  6. exec 200>"$LOCKFILE"
  7. flock -n 200 || { echo "Another instance is already running. Exiting."; exit 1; }
  8.  
  9. # Configurable limits
  10. MIN_FREQ_MHZ=800
  11. MAX_FREQ_MHZ=3700
  12. STEP_SMALL=50
  13. STEP_MED=100
  14. STEP_LARGE=800
  15. INTERVAL=7 # seconds between checks
  16.  
  17. # Helper: Set CPU frequency
  18. set_freq() {
  19. local freq="$1"
  20. sudo cpupower frequency-set -u "${freq}MHz" -d "${freq}MHz" > /dev/null
  21. echo "Set CPU frequency to ${freq}MHz"
  22. }
  23.  
  24. # Helper: Read CPU temp in °C
  25. read_temp() {
  26. sensors 2>/dev/null | awk '/Package id 0:/ {gsub(/\+|°C/, "", $4); print int($4)}' | head -n1
  27. }
  28.  
  29. # Helper: Get current CPU frequency (MHz, rounded down)
  30. get_current_freq() {
  31. awk '/cpu MHz/ {printf "%.0f\n", $4; exit}' /proc/cpuinfo
  32. }
  33.  
  34. # Initialize
  35. echo "Starting thermal governor with range ${MIN_FREQ_MHZ}-${MAX_FREQ_MHZ} MHz"
  36. current_freq=$(get_current_freq)
  37. prev_freq=$current_freq
  38. set_freq "$current_freq"
  39.  
  40. # Loop
  41. while true; do
  42. temp=$(read_temp)
  43.  
  44. if [[ -z "$temp" ]]; then
  45. echo "Could not read temperature. Retrying in 1s."
  46. sleep 1
  47. continue
  48. fi
  49.  
  50. echo "Temp: ${temp}°C | Current freq: ${current_freq}MHz"
  51.  
  52. if (( temp >= 59 )); then
  53. (( current_freq -= STEP_LARGE ))
  54. echo "Temp ≥ 59°C → Dropping by ${STEP_LARGE}MHz"
  55. elif (( temp >= 55 )); then
  56. (( current_freq -= STEP_MED ))
  57. echo "Temp >= 55°C → Dropping by ${STEP_MED}MHz"
  58. elif (( temp >= 51 )); then
  59. (( current_freq -= STEP_SMALL ))
  60. echo "Temp > 51°C → Dropping by ${STEP_SMALL}MHz"
  61. elif (( temp < 46 )); then
  62. (( current_freq += STEP_SMALL ))
  63. echo "Temp < 46°C → Raising by ${STEP_SMALL}MHz"
  64. else
  65. echo "Temp stable (46–51°C). No change."
  66. fi
  67.  
  68. # Clamp frequency to safe bounds
  69. if (( current_freq < MIN_FREQ_MHZ )); then current_freq=$MIN_FREQ_MHZ; fi
  70. if (( current_freq > MAX_FREQ_MHZ )); then current_freq=$MAX_FREQ_MHZ; fi
  71.  
  72. # Only set frequency if it changed
  73. if (( current_freq != prev_freq )); then
  74. set_freq "$current_freq"
  75. prev_freq=$current_freq
  76. else
  77. echo "Frequency unchanged at ${current_freq}MHz. No command sent."
  78. fi
  79.  
  80. sleep "$INTERVAL"
  81. done
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement