Purge memory trick

Purge Memory

Linux does a good job when it comes to memory allocation. If memory isn’t being used or hasn’t been used for awhile it gets put into a cache where it can readily pulled. At times though this cache can become pretty big (especially for a program that has a memory leak). If a good number of programs are being used or if memory is limited then Linux will begin using hard disk swap which can really bog down performance. In these instances, it may help to purge the memory.

In the terminal type free -m to see memory usage. Flushing the filesystem buffers and to drop extra caches can be done by doing:

sudo sync
sudo echo 3 | sudo tee /proc/sys/vm/drop_caches

Look once more at free -m and memory usage should be improved. Freeing memory is most effective by shutting down whatever programs can be. To be really effective shutdown X server first.

This can be put in a script if you need to regularly do this:

#!/bin/bash
# Free unused memory
flush_mem () {
sudo sync
echo 3 | sudo tee /proc/sys/vm/drop_caches
}
echo -e "\nMemory usage before purge:\n" && free -m
flush_mem || exit && echo " Error purging memory"
echo -e "\nMemory usage after purge:\n" && free -m
view raw purge-memory hosted with ❤ by GitHub

9 thoughts on “Purge memory trick

  1. Pingback: Membersihkan Memory RAM secara manual di linux « #!/Dwi/Nanto’s

  2. überRegenbogen

    This is considerably more complex that it needs to be (I dare say that you’re a tad sudo happy. ;P)

    ‘sync’ normally shouldn’t require root privileges.
    ‘echo’ really doesn’t (and is internal in most shells).
    All ‘tee’ does it show you the 3—which doesn’t accomplish much.

    So the crux of this is: “echo 3 >/proc/sys/vm/drop_caches”

    Which doesn’t have the affect that i’d hoped (i was looking for something to discourage swap use—à la “swapoff -a ; swapon -a”, but less aggressive); but it may be helpful, nonetheless. Thanks! ☺

    Reply
  3. überRegenbogen

    Oh i suppose the purpose of tee was for the file writing to happen during sudo (which i rarely use). So, for the sudo fans:

    sudo sh -c ‘echo 3 >/proc/sys/vm/drop_caches’

    or

    echo 3 | sudo tee /proc/sys/vm/drop_caches

    Reply

Leave a comment