Autoadjusting Linux VM Swappiness

I was reading a blog post about adjusting the level of swapping the linux kernel would do, and it linked to a kernel patch that would auto adjust that level. I usually just use the latest kernel supplied by the various distributions, so I don't want to patch my kernel every time there is an upgrade. That's why I made a simple shell script to be run at boot time, that will adjust the swappiness level every second.

Now, the swappiness level is adjustet in /proc/sys/vm/swappinessby a number ranging from 0 to 100, 0 being almost no swapping and 100 being a lot of swapping. So, based on the method used by the kernel patch, the script I wrote will find the percentage of RAM used by applications, and set the swapping level to that. For instance, if my desktop computer have got 8Gb of RAM, and 1.2Gb of RAM is used by applications, that would result in a RAM usage of 15%. The script will then set the swappiness to 15. Below is the script:


# will adjust the current swappiness of the kernel
# based on the idea by Con Kolivas (
total=$(grep MemTotal /proc/meminfo | awk '{ print $2 }')
while [ true ]; do
  used=$(grep AnonPages /proc/meminfo | awk '{ print $2 }')   
  result=$(echo $used \* 100 / $total | bc -q)
  echo $result > /proc/sys/vm/swappiness
  sleep 1

This script should be run at boottime.

Written by Jannich Brendle ons 28 oktober 2009 In How to

tags: bashhacklinux

Related posts