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/swappiness by 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:

#!/bin/sh

# will adjust the current swappiness of the kernel
# based on the idea by Con Kolivas (http://kerneltrap.org/node/1044)
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
done

This script should be run at boottime.
If you got any suggestions, please write below. :-)

Related posts:

Tags: , ,

2 Comments to “Autoadjusting Linux VM Swappiness”

  1. Nikesh says:

    Don’t you think running the script all time (while [true]) will consume lot of cpu hence can bring down the processing power of the machine.

  2. Hi Nikesh. :-)

    No, not at all, since I use the sleep command. :-)

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This site uses KeywordLuv. Enter YourName@YourKeywords in the Name field to take advantage.