Setting the CPU Frequency Govenor from the Command Line

Most modern processors support some level of frequency scaling, that is they change the speed or frequency that they are running at in order to reduce energy consumption. You can usually change the frequency with a GUI app but what happens if there is no GUI running (on say a server). The command is called cpufreq-set. You can get details (like processor statistics and current governor in use. Both of these are provided by the cpufrequtils package which you can just apt-get or aptitude install

The problem is that cpufreq-set only sets one core or CPU at a time. On a dual or quad socket this could get quite tedious. Fortunately there is an easy solution.

  1. for each in `cat /proc/cpuinfo |grep processor |cut -f 2 -d \:` ;do sudo cpufreq-set -c $each -g performance ; done

What I do is run a small little bash script that iterates over all the CPUs and sets the governor to one set as a parameter to the script.

  1. #!/bin/bash
  2. # Wrapper to easily set the CPU Frequency Governor
  3.  
  4. # Check that a valid governor is set
  5.  
  6. GOVERNOR=$1
  7.  
  8. USAGE="This script requires a CPU governor as an argument, which should be one of: conservative, ondemand, userspace, powersave, performance
  9. For example: cpuscale.sh ondemand"
  10.  
  11. if [ "$#" = "0" ]; then
  12.         echo "$USAGE"
  13.         exit 1
  14. fi
  15.  
  16. # Creating an array with each of the CPUs numeric ID
  17. declare -a  CPUs=( `cat /proc/cpuinfo |grep processor |cut -f 2 -d \:` )
  18.  
  19. # This computes the number of elements in the array, we use this to control our loop in the SetSpeed function
  20. elements="${#CPUs[*]}"
  21.  
  22. SetSpeed ()
  23. {  
  24.   for (( i = 0  ; i < $elements ; i++ ))
  25.   do sudo cpufreq-set -c ${CPUs[$i]} -g $GOVERNOR
  26.   done
  27. }
  28.  
  29. echo "Setting CPU Frequency Governor"
  30. SetSpeed
  31. echo "Done"