489

When I open a RAM-intensive app (VirtualBox set at 2GB of RAM), some swap space is generally used, depending on what else I have open at the time.

However, when I quit that last application, the 2GB of RAM is freed up, but the same swap space use remains.

For example, right now, about two hours after having closed VirtualBox, I have 1.6GB free RAM and still 770MB in swap.

How can I tell Ubuntu to stop using that swap and to revert to using the RAM?

Flyk
  • 1,480
jfoucher
  • 23,534
  • 1
    The easiest thing reboot your device and save time of coping to ram and free ram save power of laptop and cpu temperature – Mohamed Slama Jun 13 '16 at 04:18
  • 9
    Big assumption that repopulating all the stuff on your computer takes less time than that. – Jono Apr 24 '17 at 18:06
  • 3
    Ubuntu 16.04, at least, can keep using swap long after it was needed thusly making your system orders of magnitude slower by relying on the swap file even though no longer a necessity. The manual intervention can therefore by useful. Rebooting is not always an option. – matanox Mar 14 '19 at 09:24

8 Answers8

699

The Linux kernel underlying Ubuntu will automatically "swap in" those pages from disk to RAM as needed, so in general I'd say just let it happen naturally.

However, if you really feel that you need to force it, (I can see a scenario where you would want to know the system will be responsive later) you can momentarily disable and re-enable swap

sudo swapoff -a
sudo swapon -a

OR alternatively as a single line

sudo swapoff -a; sudo swapon -a

Be careful doing this, as you may make your system unstable, especially if its already low on RAM. Be sure to have enough free RAM in your system, or you might not be able to free the swap and the OOM-Killer would end up killing some of your processes.

Note that the swapoff may take a while. This is particularly true if you have lot of swap to be swapped off.

Valerio Bozz
  • 249
  • 2
  • 12
SpamapS
  • 19,820
  • 11
    That did the trick, the swap was copied to ram. I guess you just need to make sure to have at least the amount of swap used as free ram before running swapoff, right? – jfoucher Aug 06 '10 at 08:22
  • 13
    The swap was not copied to RAM. It was merely disabled. You should ensure the box is not swapping before doing this. If you do, then the kernel will see the memory disappear and the OOM-Killer will probably start killing off applications arbitrarily. There's no reason you should need to 'clean' out the swap like this. (see my other comment) :) – popey Aug 06 '10 at 10:06
  • 69
    Actually the swap is, basically, copied to ram, or more accurately, the pages are swapped back in from disk to RAM before the swap can be disabled. – SpamapS Aug 07 '10 at 15:00
  • 16
    The pages are copied to RAM only if they are still needed by some process. Sometimes a swapped page belongs to a process that has already been finished, and the kernel doesn't care to remove these pages from swap immediately. – Bruno Medeiros Dec 30 '13 at 14:57
  • 11
    This should be the correct answer, as it is the way to get the swapped pages back to RAM and then empty the swap memory – Alfonso Jiménez May 05 '16 at 08:58
  • 7
    This is the single answer that actually answers the question, and should be the accepted one! – pagliuca Dec 10 '16 at 14:14
  • 1
    You can view the progress (to get a rough idea of how long it will take) using watch free -h, the total swap and used swap will go down as it's being moved. – Shelvacu Mar 30 '17 at 18:31
  • This indeed does the job. But it is not worth it in my case: I swapped 4Gb into mem and it took 3 min: first 2.5 min nothing happened and the swap was only swapped in the last 30 seconds. – HongboZhu Jun 22 '17 at 13:56
  • 1
    I actually made myself a shell script that does just this and put to /usr/bin/reswap. Now I can do this with one command. – unfa Jun 29 '17 at 09:36
  • 2
    I am looking at creating a Nagios alert that warns us when a system has started to swap. For example, at this moment I have a system with 8/16G swap used, but only 36/128G RAM in use. If Nagios is alerting, I'd like to clear the swap so it quiets down. I know the swap isn't being used at this moment, but Nagios doesn't. So here's one use case where being able to "flush" the swap space would be handy... as simply a bookkeeping exercise. – Mike S May 30 '18 at 13:26
  • @jfoucher I think you should mark this answer as the correct answer, given that it actually answers the specific question that you asked. The current correct answer, deals more with explaining the working of swap out and swap in rather than how to clean out the swap and move it to memory. Also, see Scott Severance's answer for a script to do the same thing. – kapad Aug 09 '18 at 05:48
  • swapoff: -a, --all disable all swaps from /proc/swaps .................. .................. .................. swapon: -a, --all enable all swaps from /etc/fstab (if you are using e.g. manual swap file, you have to add it yourself again, swapon -a won't do it :) ) – jave.web Nov 27 '18 at 06:05
  • 2
    in my experience swapoff may take a very looooooong time to complete draining the swap file back to RAM. not sure why. – matanox Mar 14 '19 at 09:24
  • I don't actually experience this happening

    "The Linux kernel underlying Ubuntu will automatically "swap in" those pages from disk to RAM as needed"

    – matanox Mar 14 '19 at 09:28
  • 2
    IMHO one should not use && but rather a semicolon (swapoff -a; swapon -a) instead! Why? Suppose you're having multiple swap devices. swapoff then might succeed on one device, but fail on the other. In such a case, the swapoff command will return a non-zero exit code, causing the swapon -a command not to be executed, hence ending up with less swap space than before! – myrdd Jun 16 '19 at 12:36
  • Is there a way to do this for single processes? They could be stopped, everything moved to RAM and then continued... – Radio Controlled Sep 27 '19 at 09:37
  • I was expecting swap to be moved to RAM quickly, but in fact there is no "transfer". It just disable swap, and swap is emptying as long as applications free memory. So it can take few minutes. But I could stop it with ctrl+C: swap just enables back with the rest of data. – Alcalyn Oct 21 '19 at 16:21
  • @Shelvacu btw another way to watch the progress - with GUI - (e.g. if you're on Ubuntu) is the embedded System Monitor which shows swap usage. – whyer Dec 28 '19 at 03:42
  • 1
    @matt i confirm that it's very slow, but you haven't say HOW MUCH slow it is (this may be interesting to someone). in my case it's about 1 MB per second. e.g. if i have 8 gb ram & 8 gb swap and my swap is 15% used then it'll take approx. 20 minutes to free it! that's loooooong. all that time, one of my cpu cores is 100% busy. i have 4 cores -> cpu is 25% busy. maybe this info will be helpful for someone who's deciding whether should they try it – whyer Dec 28 '19 at 03:48
  • Life just got so much better with this level-up command! No more need to reboot my Debian. Every Linux user should know these commands. – Brian Cannard Jan 04 '20 at 18:25
  • Depending on how long it takes to move everything out of swap, it might be better to run sudo bash -c "swapoff -a; swapon -a" to avoid off chance that you might have to enter your password twice. – b_laoshi Jan 20 '20 at 03:19
  • Is it safe, doing this on a live system, e.g. with a DB? Would it noticeable slow down everything while swapoff/swapon is running? – robsch Aug 24 '20 at 09:46
  • is sudo swapoff -a going to keep in disabled forever? I don't care about swap because I have 64GB or RAM and it only makes things slowdown. – m4l490n Jul 29 '22 at 16:23
222

Just because swap is allocated, doesn't mean it's being 'used'. Whilst programs like system monitor and top will show some of your swap space being allocated (in your example 770MB) that doesn't mean that the system is actively swapping in/out.

To find out if anything is swapping in/out you can use the vmstat command. Leave it running a few seconds to settle down and watch the si (swapin) and so (swapout) columns. If nothing is happening then there is no reason to be concerned.

Here's the output of running vmstat 1, where you can see my machine is not swapping at all.

procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 0  0  78588 230788   9596  72196    0    0     0     0  543  652 12  6 78  0
 0  0  78588 230780   9596  72196    0    0     0     0  531  410  1  0 99  0
 0  0  78588 230796   9596  72196    0    0     0     0  300  335  1  1 97  0
 1  0  78588 230788   9608  72224    0    0    40     0  737  762  4  4 84  8
 5  0  78588 230788   9608  72224    0    0     0     0  415  385  9  3 84  0
 0  0  78588 230540   9616  72224    0    0     0    44  611  556 55  5 31  0
 0  0  78588 230532   9616  72224    0    0     0     0  574  662  1  6 89  0

Yet here in top you can see I have swap space allocated:-

Mem:    475236k total,   245076k used,   230160k free,     9720k buffers
Swap:   491512k total,    78588k used,   412924k free,    72476k cached
Yi Jiang
  • 1,206
popey
  • 23,667
  • 54
    “no reason to be concerned”, up to the point when I continue to use some application that was swapped out. then all hell breaks loose. – törzsmókus May 13 '14 at 12:14
  • 291
    This post doesn't answer the question. – emchristiansen Jun 25 '14 at 20:45
  • 23
    The premise of the question is based on misconceptions. This post addresses the misconceptions. – popey Jun 26 '14 at 10:11
  • 52
    I don't see a misconception, I see a disagreement about what "used" means. You are meaning "used" to refer to actively swapping in/out, while the original question appears to be posed with "used" meaning that there is data that has been swapped out, which may later need to be swapped back in. There are valid reasons to want to flush the swap after an event that swaps out a lot of other memory, essentially pre-empting the active swapping that the user knows will occur later (especially if the later 'de-swapping' is likely to occur while the disk is under load for other reasons). – drfrogsplat Oct 10 '14 at 02:09
  • 56
    After running a memory intensive application, my other applications are unrepsonsive when I switch to them, presumably due to being swapped. Some way of telling the system to un-swap as much data as possible (followed by a coffee break) would be better than having to wait 20s every time I Alt+Tab. – Mark K Cowan Nov 01 '14 at 11:18
  • I tried vmstat and si & so where idle. Then I tried swapoff. This time, I can see the swap is getting reduced and the main memory is getting allocated. –  Feb 16 '16 at 13:11
  • 5
    The title of the question is specifically asking about emptying swap. For example, the Oracle installer won't run some (any) commands if there is less than 500 MB of swap available, it doesn't matter if there is 200+GB of free RAM. Whether the swap is being actively used, something is using it by sitting there. In most cases inactive swap use might make it slow to switch tasks, while other cases it breaks functionality. – jbo5112 Jun 20 '16 at 21:02
  • 3
    This does not answer the question! – pagliuca Dec 10 '16 at 14:14
  • 1
    This is also useless for times when your swap has useless data inside it. I once used the swapoff swapon trick on a 2GB swap and it only took 500MB while it was active in the memory. – John Hamilton Sep 14 '17 at 05:38
  • I have done this but now htop says there are 0k/0k of swap used, like if the swap is not available anymore... – Fez Vrasta Jan 25 '18 at 13:39
  • 2
    "If nothing is happening then there is no reason to be concerned.", I find this hard to believe. I had memory intensive calculations force the use of swap, after killing the calculations and having a surplus of RAM again, swap stayed filled and firefox was responding slow. Killing firefox emptied a lot of swap, after restaring firefox was fast again. I expect that the OS doesn't always operate efficiently regarding swap. – Herbert Aug 01 '18 at 11:25
  • @emchristiansen It does better than answer, but gives some insight into the inner workings of the kernel and paging. – Louis Waweru May 02 '20 at 04:06
  • This does not answer the question. The application I am working with will crash unless a certain amount of swap is available when I start it. It does not matter that Linux is not swapping in/out. – Étienne Jan 16 '23 at 09:40
183

You can also set your "swappiness" value from the default of 60, this way the swap won't grow so large to begin with. Why the shipping default is set to 60 when the recommended value is 10 perplexes me. From the Ubuntu SwapFAQ:

The default setting in Ubuntu is swappiness=60. Reducing the default value of swappiness will probably improve overall performance for a typical Ubuntu desktop installation. A value of swappiness=10 is recommended, but feel free to experiment.

By changing this value to 10 or even 0, you can add a significant and perceivable speed boost to an older system with a slow drive. Setting this value to 0 does not turn swap off for Linux kernel 3.4 and below but with 3.5+ it does so you will want to use a value of 1 if you want to keep it on its lowest setting*.

I see no reason not to set this to 0 since anything that hits disk is slower than RAM. I have 8 virtual cores, a fast SSD & 8 GB of memory and my swap is set to 0. As of this moment I have 3 virtual machines running, my memory usage is 7.1 of 7.7 GB, my used swap is only at 576KB of 952MB and all systems are running smoothly!

From the Ubuntu SwapFAQ:

The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. Because disks are much slower than RAM, this can lead to slower response times for system and applications if processes are too aggressively moved out of memory.

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

Below are basic instructions for checking swappiness, emptying your swap and changing the swappiness to 0:

To check the swappiness value:

cat /proc/sys/vm/swappiness

To temporarily set swap to 0 (as suggested by SpamapS):

This will empty your swap and transfer all the swap back into memory. First make sure you have enough memory available by viewing the resources tab of gnome-system-monitor, your free memory should be greater than your used swap. This process may take a while, use gnome-system-monitor to monitor and verify the progress.

sudo swapoff --all

To set the new value to 0:

sudo sysctl vm.swappiness=0 

To turn swap back on:

sudo swapon --all

To permanently set swappiness to 0:

  1. sudoedit /etc/sysctl.conf
  2. Add this line vm.swappiness = 0
  3. sudo shutdown -r now # restart system

* With kernel version 3.5+ setting swappiness to 0 does turn it off entirely and a setting of 1 is recommended if you want the lowest swappiness algorithm. source: https://www.percona.com/blog/2014/04/28/oom-relation-vm-swappiness0-new-kernel/

Elijah Lynn
  • 3,828
  • 2
    I just updated the answer to include a permanent way to set swappiness. Not sure how it got upvoted so much, I am guessing nobody tested it. – Elijah Lynn Jul 01 '15 at 13:23
  • 1
    More good reading on swappiness in this answer => http://askubuntu.com/a/103916/11929 – Elijah Lynn Jul 01 '15 at 13:24
  • Added a note about the behavior of swappiness=0 changing with Linux kernel version 3.5+. – Elijah Lynn Jul 01 '15 at 13:37
  • Hi. Thanks for this good answer. I suggest, as you said in the last lines (with *), to modify accordingly also your entire answer (that means set swappiness to 1 as preferred, not 0). This would make the answer more consistent, I believe. – miro marchi Nov 21 '15 at 09:05
  • 3
    I'm not sure if this was available when the author originally posted the answer but a swappiness value of "60" is in place for ubuntu server installs since that environment has a different set of specifications for performance. https://help.ubuntu.com/community/SwapFaq#What_is_swappiness_and_how_do_I_change_it.3F – Frito Jun 06 '16 at 14:10
  • why do you have swap in the first place when you then set the swappiness to 0? If you really want to disable swap I'd prefer to grab back that disk space ^^ – xeruf May 06 '18 at 15:24
  • Because there is no way to turn swapiness off in 3.4 and lower kernels, the only way is to set swapiness to 0, in 3.5 and later swapiness 0 this is how you disable it. – Elijah Lynn May 07 '18 at 03:57
  • 3
    This setting is very effective in controlling the size of the swap. My system has 16G RAM and 16G swap. Sometimes I'm running to VMs and some of my applications get swapped out. When I close the VMs the RAM usage drops, but the swap usage remains the same and my system lags when changing applications. Changing the swapiness has improved performance for me. – kapad Aug 09 '18 at 05:46
  • 2
    This should be the accepted answer really. Thorough explanation of the problem, and it's solution, as well as links and a solution to retain Swap memory, but help keep it under control in the first place. Awesome stuff. Thanks. :) – Jack_Hu Jul 24 '19 at 22:28
  • Is the 3.5+ still true? I have Kernel 4.15 with swappiness 0, swap still works (but only when really needed) – jave.web Aug 13 '19 at 13:16
  • I actually have the best results (regarding responsivity and swap times) using a swappiness value of 70 or even 80 (Arch Linux, kernel 5.3). Yes, using a lower swappiness value makes the kernel swap memory less often, but when it does... Good luck waiting up to 5 minutes until getting control of your mouse cursor back. – Marc.2377 Sep 28 '19 at 16:22
61

I've found that emptying swap can help a lot on systems with slow disks and limited RAM. Of course, as already mentioned, the way to do this is to run sudo swapoff -a; sudo swapon -a. The problem here is that if there's insufficient RAM, doing so will cause all sorts of problems.

I've written a script that I call toggle_swap that has worked for me for the last several years. It checks for enough free RAM before actually disabling the swap. Here it is:

#!/bin/bash

free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"

echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"
if [[ $used_swap -eq 0 ]]; then
    echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $total_free ]]; then
    echo "Freeing swap..."
    sudo swapoff -a
    sudo swapon -a
else
    echo "Not enough free memory. Exiting."
    exit 1
fi
  • Awesome I was looking for something like this. Maybe to be a little safer you could present the number and percentages and then ask, just to be absolutely sure. – Atherion Jan 27 '17 at 00:09
  • 4
    I've update the code and have created a gist based https://gist.github.com/Jekis/6c8fe9dfb999fa76479058e2d769ee5c – Jekis Aug 24 '17 at 08:06
  • This is the conclusion I reached after reading all the tips, like one should somehow make sure there is enough RAM indeed before killing swap. Thank you sir, wonderful script. Should be included in Ubuntu by default (not kidding, it really is a musthave.) – Apache Aug 28 '17 at 18:55
  • Except that if you run any new thing while turning off swap, and before it's back on - it won't have enough memory. – barteks2x Nov 02 '17 at 16:38
  • That depends on how much free memory you have. If there's enough free memory to hold everything in swap AND the new process, then there's no issue. If not then you're right. – Scott Severance Nov 03 '17 at 12:56
  • Does this really work better than just reducing /proc/sys/vm/swappiness from the default 70 down to 10 or 20? The kernel will still swap when needed, but is less aggressive about it. Do you actually find your system getting slow, or do you just like seeing low swap-usage numbers? – Peter Cordes Nov 06 '17 at 22:15
  • Oh, you're using this manually instead of having everything be slow the first time you use it. A recent question was asking about swapoff/swapon from an hourly cron job, and an answer linked here. IMO, that sounds like a bad idea even if you do check to make sure there's enough memory. This is a good answer to this question, for a manual unswap-everything script. – Peter Cordes Nov 06 '17 at 22:23
  • I got
    Freeing swap...
    swapoff: /dev/sdb5: swapoff failed: Cannot allocate memory
    swapoff: /dev/sda5: swapoff failed: Cannot allocate memory
    
    – Constantin De La Roche Dec 07 '20 at 19:15
  • Try running swapoff and swapon manually and see if you get errors that way. If so, that's a separate issue. – Scott Severance Dec 07 '20 at 20:29
  • 2023 - Works for a PopOS 22.04 box – MarcoZen Apr 12 '23 at 07:00
  • @ScottSeverance Computing free_mem + buffers + cache result to more than total!! See my answer (Your use of fork to awk is overkill) – F. Hauri - Give Up GitHub Dec 22 '23 at 08:05
26

After mucking around with swappiness for a couple of days, I've come to the conclusion that the kernel should be left to its own devices. It knows what it's doing, and it's optimized to give you the best experience.

Unless you have a really good reason for wanting that disk back, I'd leave it be.

Erigami
  • 4,476
  • 9
    I had some stuff in swap, vmstat showed me that swapin and swapout was happening, and Chrome was laggy af, while my CPU was barely used. Good enough reason, no? – xeruf May 06 '18 at 15:27
  • 1
    There are definitely cases where certain swapping on desktop makes it laggy. (not while it is swapping, but also after, when there is enough RAM, for long time after.) So at best this answer is only subjective experience which happens in some cases. – Cray Sep 26 '19 at 20:02
2

New anser 2023!

Some tips and tricks

In addition to all existing answer I want to share some tricks I use.

Reading free's output

First, ensure that output of free is not localized, for this you have to prepend command by LANG=C free -k:

               total        used        free      shared  buff/cache   available
Mem:        32739720     9436264     8704992      883044    15959152    23303456
Swap:       23437308     5450752    17986556

Where, if you compute buff/cache + available the result will be bigger than total! This is wrong!!

Just consider if available mem is bigger than used swap, before purging swap!

msgs=("NOT " "")
{ # read `free` output, ignore 1st line and all values but free and swaped.
    read _
    read -r _{,,,,,} avail
    read -r _ _ swaped _
} < <(LANG=C free -k)
printf 'Avail: %d swaped: %d Can %sunswap!\n' \
           "$avail" "$swaped" "${msgs[ avail > swaped ]}"
 Avail: 23303456 swaped: 5450752 Can unswap!

Alternative using /proc/meminfo instead of free

Accessing directly /proc/meminfo instead of running a fork to free, you could obtain same values by:

msgs=("NOT " "")
while read field val _; do
    case $field in
        MemAvailable: ) avail=$val ;;
        SwapTotal: )    declare -i swaped=$val ;;
        SwapFree: )     swaped+=-$val; break ;;
    esac
done < /proc/meminfo
printf 'Avail: %d swaped: %d Can %sunswap!\n' \
           "$avail" "$swaped" "${msgs[ avail > swaped ]}"
 Avail: 23303456 swaped: 5450752 Can unswap!

Purging swap swapoff -a.

I've build a little script that

  • correctly parse free's output,
  • show human readable swaped and avail memory,
  • offer to run swapoff - swaponn loop if user don't interact
  • then compute elapsed time used to unswap.

There is my script, based on bash V>5.0:

#!/bin/bash

msgs=("NOT " "") while read field val _; do case $field in MemAvailable: ) avail=$val ;; SwapTotal: ) declare -i swaped=$val ;; SwapFree: ) swaped+=-$val; break ;; esac done < /proc/meminfo

txtsize() { # Convert integer into readable string, store result in $2 varname local i=$(($1>=1<<50?5:$1>=1<<40?4:$1>=1<<30?3:$1>=1<<20?2:$1>1023?1:0)) local a=(K M G T P) ((i>4?i+=-2:0)) && a=(${a[@]:2}) && set -- $(($1>>20)) $2 local r=00$((1000$1/(1024*i))) printf -v $2 %.2f%s ${r::-3}.${r: -3} ${a[i]} }

txtsize $avail havail txtsize $swaped hswaped printf 'Avail: %s (%d) swaped: (%s) %d Can %sunswap!\n'
"$havail" $avail "$hswaped" $swaped "${msgs[ avail > swaped ]}"

if (( avail > swaped )); then
    if read -sn 1 -t 5 -p\
        'Proceed in 5 seconds. Hit any key to stop now. '; then
        echo $'\nUser abort.'
            exit 0
    fi
    echo
    elapsedTime=${EPOCHREALTIME/.}
    swapoff -a
    elapsedTime=00000$(( ${EPOCHREALTIME/.} - elapsedTime ))
    swapon -a
    elapsedMin=$(( 10#$elapsedTime / 60000000 ))
    elapsedSec=00000$(( 10#$elapsedTime % 60000000 ))
    printf 'Swap: %s purged in %d minutes and %.3f secs (%.4f").\n' \
        "$hswaped" "$elapsedMin" ${elapsedSec::-6}.${elapsedSec: -6} \
        ${elapsedTime::-6}.${elapsedTime: -6}

fi    

His ouptut look like:

Avail: 23.86G (25023596) swaped: (1.14G) 1192460 Can unswap!
Proceed in 5 seconds. Hit any key to stop now. 
Swap: 1.14G purged in 1 minutes and 51.166 secs (111.1661").

This script require root privilege. But you could edit them to add sudo before swapoff -a and swapon -a.

From there, as this opereation could take some time, I've built a Full purgeSwap script, showing progression with a nice progress bar and compute end time estimation, you my download here: purgeSwap.sh.

This answer is linked to this other one: How to find out which processes are using swap space in Linux?

About swapiness

I'm not totally convinced on how this compute percent of used memeory: including swap or not... For my tests, I'v seen swaping a lot before reaching percents configured in this kernel variable.

Anyway, for my servers, I still use:

echo 10 > /proc/sys/vm/swappiness

for running system that was not already configured by:

echo >/etc/sysctl.d/90-swapiness.conf  'vm.swappiness = 10'

before last reboot.

Use of vmstat 1

I often use this, but as I like graphical presentation, I've build (in 2009) a perl CGI, that could work in standalone:

http://perso.f-hauri.ch/~felix/marcm/vmstat.cgi

This script is self-downloadable, work in any web server, but could be used directly on poor systems. Graphics are drawn in svg and rendered by your browser.

Sample of use:

wget -O vmstat.pl http://perso.f-hauri.ch/~felix/marcm/vmstat.cgi/download/vmstat.cgi
LANG=C perl vmstat.pl 
CGI::Pretty is DEPRECATED and will be removed in a future release. Please see https://github.com/leejo/CGI.pm/issues/162 for more information at /usr/share/perl5/CGI/Pretty.pm line 20.
Server started at port 8881

Yes, it's an old script Don't run them as root!!.

...Then you could connect with a browser:

http://ip.add.re.ss:8881/

http://127.0.0.1/?delay=1&width=1800&height=120

Here 1'800 dots with a delay of 1 seconds make half hour graphs.

0

Tell the vm to not be so swappy, by resucing the swappiness, by

sudo sysctl vm.swappiness=10

or even not be swappy as much as possible by

sudo sysctl vm.swappiness=0

Please read the documentation of swapfile here: https://help.ubuntu.com/community/SwapFaq

-3

It doesn't affect performance if your swap space is occupied. The only performance penalty is is stuff is going in/out of swap. If nothing is being swapped in/swapped out, then you don't have to worry about anything.

Amandasaurus
  • 1,816
  • 13
    Yeah but if something is being swapped it does affect performance, hence this question. – quant Feb 03 '15 at 22:18
  • 1
    That is some real nonsense, usually big fallback swaps are on HDDs or generally on a slower device than RAM - if space runs out - existing stuff is swapped - like e.g. internet browser - and then you're practically using it from the slower device... – jave.web Aug 13 '19 at 13:22
  • Memory is usually being swapped way before RAM space is running out. This is controlled by the vm.swappiness parameter. As soon as swap space is occupied there will be a performance impact when a memory page is accessed that has been swapped out to disk. – lanoxx Mar 16 '20 at 16:40