Empty Swap

From ArchWiki

Jump to: navigation, search


Contributor: Ibex

I'm using a laptop so my hard disk is quite slow. Therefore the whole system is getting slow when swap is being used. Here is my solution to this problem.

Contents

[edit] Why?

An example: When viewing a website with a lot of graphic elements it is possible that the RAM is getting full so the system is going to use its swap space. That's good. But once that website has been viewed and the memory has been freed, it just so happens that the swap is still in use because parts of running programs have been swapped out and are not placed back into RAM; Therefore those programs will still react slow.

I was tired of this problem so I decided to write a very small script to put the swap data back into RAM.

Beware: You have to be sure that the data which is currently in the swap can be placed into RAM. So make sure you have enough free RAM for this otherwise the system will crash. The script has no check for this!

[edit] The script

As root, create a file named "emptyswap", and paste the following into the file:

echo -e "\noutput of free before:" &&
free &&
swapoff -a && swapon -a &&
echo -e "\noutput of free after:" &&
free &&
echo -e ""

[edit] Getting things working

Save the file. Make it executable and move it to /usr/bin

chmod +x emptyswap && mv emptyswap /usr/bin

You can simply run the script by typing the following as root:

emptyswap

The output will look similar to this:

[root@laptop ibex]# emptyswap

output of free before: total used free shared buffers cached Mem: 515076 257964 257112 0 3672 53396 -/+ buffers/cache: 200896 314180 Swap: 489972 199804 290168

output of free after: total used free shared buffers cached Mem: 515076 383988 131088 0 3712 55516 -/+ buffers/cache: 324760 190316 Swap: 489972 0 489972

[root@laptop ibex]#

[edit] Conclusion

You can see the swap is now empty but the RAM is almost full. This is not a problem as the system will soon free the RAM a little bit. Other programs will now run fast without having to wait for the swap to find the needed data.

Feel free to improve the script, and post your improvements on the forum.

[edit] All above with ram test

-----------------
#!/bin/sh
msg="cannot write swap back to ram...\nnot enough memory - bye..."
mem=`free|grep Mem:|awk '{print $4}'`
swap=`free|grep Swap:|awk '{print $3}'`
test $mem -lt $swap && echo -e $msg && exit 1
echo -e "\noutput of free before:" &&
free &&
swapoff -a && swapon -a &&
echo -e "\noutput of free after:" &&
free &&
exit 0
-----------------
Personal tools