How to Clear Memory Cache in Linux
You can write to /proc/sys/vm/drop_caches file to instruct kernel to drop clean caches, as well as reclaimable slab objects like dentries and inodes. Once dropped, their memory becomes free.
This is not recommended to clear memory cache on Linux systems, but it is safe. But clearing cache may cause performance issue with system. Since it discards cached objects from memory, it may cost a significant amount of I/O and CPU to recreate the dropped objects.
This tutorial will help you to clear memory cache on Linux/Unix system via command line.
How to Clear Cache in Linux System
There are three options available to clear cache in Linux system memory. Use one of below as per your requirements.
- Clear PageCache, dentries and inodes in cache memory
1 2 3
sync; echo 3 | sudo tee /proc/sys/vm/drop_caches Or sync; echo 3 > /proc/sys/vm/drop_caches Or sync; sysctl -w vm.drop_caches=3
- Clear dentries and inodes only in cache memory
1 2 3
sync; echo 2 | sudo tee /proc/sys/vm/drop_caches Or sync; echo 2 > /proc/sys/vm/drop_caches Or sync; sysctl -w vm.drop_caches=2
- Clear pagecache only in cache memory
1 2 3
sync; echo 1 | sudo tee /proc/sys/vm/drop_caches Or sync; echo 1 > /proc/sys/vm/drop_caches Or sync; sysctl -w vm.drop_caches=1
Here the sync command is used to increase the number of objects freed by the drop cache. Using this a user can claim more memory by clearing more dirty objects on the system.
上面三种方式都是临时释放缓存的方法,要想永久释放缓存,需要在/etc/sysctl.conf文件中配置:vm.drop_caches=1/2/3,然后sysctl -p生效即可!
另外,可以使用sync命令来清理文件系统缓存,还会清理僵尸(zombie)对象和它们占用的内存
drop_caches的值可以是0-3之间的数字,代表不同的含义:
0:不释放(系统默认值) 1:释放页缓存 2:释放dentries和inodes 3:释放所有缓存
How to Schedule Clear Memory Cache
If you have to clear buffer cache regularly, use the cronjob do it. Schedule the following in system crontab to automatically flush cache memory on a regular interval.
Open a terminal and execute crontab -e command to edit crontab:
1
crontab -e
Append below entry to the file:
1
0 10 * * * sync; echo 3 | sudo tee /proc/sys/vm/drop_caches
The above cron will execute on every hour and flushes the memory cache on your system.
How to find Cache Memory in Linux
Use free command to find out cache memory uses by Linux system. Output of free command is like below
1
free -m
Output:
1
2
3
4
total used free shared buffers cached
Mem: 16050 15908 142 0 120 12953
-/+ buffers/cache: 834 15216
Swap: 0 0 0
Here the last column is showing cached memory (12953 MB) on Linux system. The -m option is used to show output MB’s.
Using SWAP
Swap用途
Swap意思是交换分区,通常我们说的虚拟内存,是从硬盘中划分出的一个分区。当物理内存不够用的时候,内核就会释放缓存区(buffers/cache)里一些长时间不用的程序,然后将这些程序临时放到Swap中,也就是说如果物理内存和缓存区内存不够用的时候,才会用到Swap。
swap清理:
1
swapoff -a && swapon -a
注意:这样清理有个前提条件,空闲的内存必须比已经使用的swap空间大