Optimize Swap Usage in Ubuntu 14.04

Swap space is the area on a hard disk which is part of the Virtual Memory of your machine. It temporarily holds memory pages that are inactive. Swap space is used when your system decides that it needs physical memory for active processes and there is insufficient unused physical memory available. If the system happens to need more memory resources or space, inactive pages in physical memory are then moved to the swap space therefore freeing up that physical memory for other uses. Note that the access time for swap is slower therefore do not consider it to be a complete replacement for the physical memory.

Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap files.

When will you need swap:

  • large program that make the entire system need extra memory.
  • hibernate will write out the contents of RAM to swap
  • extended cache memory

Optimize Swap Usage:

The swappiness parameter controls the tendency of swap usage, so you can change its value to improve overall performance for your Ubuntu desktop.

  • swappiness can have a value of between 0 and 100
  • swappiness=0 tells the kernel to avoid swapping processes out of physical memory for as long as possible
  • swappiness=100 tells the kernel to aggressively swap processes out of physical memory and move them to swap cache

Press Ctrl+Alt+T on keyboard to open the terminal. When it opens:

To check out swappiness value, run:

cat /proc/sys/vm/swappiness

If you have a LARGE RAM, you can reduce the value via:

sudo sysctl vm.swappiness=10

To make a change permanent, edit the config file via:

sudo gedit /etc/sysctl.conf

Add the below line into the end and save the file.

vm.swappiness=10

Finally reboot to apply the change.

Empty Swap:

Even if you have lots of RAM and even if you have a low swappiness value, it is possible that your computer swaps. This can hurt the multitasking performance of your desktop system.

You can use the following script to get the swap manually back into RAM:

1. place the script e.g. /usr/local/sbin:

gksudo gedit /usr/local/sbin/swap2ram.sh

copy & paste the script into the file and save it:

#!/bin/sh

mem=$(free  | awk '/Mem:/ {print $4}')
swap=$(free | awk '/Swap:/ {print $3}')

if [ $mem -lt $swap ]; then
    echo "ERROR: not enough RAM to write swap back, nothing done" >&2
    exit 1
fi

swapoff -a && 
swapon -a

make the script executable:

sudo chmod +x /usr/local/sbin/swap2ram.sh

Finally execute the script:

sudo /usr/local/sbin/swap2ram.sh

Read more

About ml

ml is a part time stay-at-home dad who've been using Ubuntu Desktop for a few years. He writes in the free time and wishes to share some useful tips with Ubuntu beginners and lovers.