free command: Releasing the disk cache

Linux uses its free memory for caching stuff which helps reduce IO . For many, this looks like memory is running low but everything is fine actually. This cached memory can be released if needed by tuning some kernel parameters. But probably nobody would like to do this except for bench marking purpose. Disk cache actually makes applications load faster and run smoother

Tuning /proc/sys/vm/drop_caches

The following is the state of  memory utilization in my desktop.

$ free -m
                    total        used       free      shared    buffers     cached
Mem:          1987       1805        181          0         230          1298
-/+ buffers/cache:        276       1710
Swap:         1906           0         1906

We can see from the first row,  "free" is reporting only 181M to be free and around 1298M has been used for disk cache.

Now let's tune  /proc/sys/vm/drop_caches to release the memory used for cache. We can specify 3 values to drop_caches. Default value is 0 which tells to cache apps. The significance of 3 values are:

To free pagecache: 

# echo 1 > /proc/sys/vm/drop_caches 
To free dentries and inodes:  
# echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:  
echo 3 > /proc/sys/vm/drop_caches

I will now configure drop_caches with a value of 1 to drop the cache. Let's now check the memory consumption status on the host.

$ echo "1" | sudo tee /proc/sys/vm/drop_caches
1
$ free -m
                    total        used       free     shared    buffers     cached
Mem:          1987        879       1108          0          0            609
-/+ buffers/cache:        269      1718
Swap:         1906          0         1906

We can now see from the first row that there is a gain of  free memory from 181M to 1108M and cached has reduced from 1298M to 609M. So ,we released some amount of RAM occupied by cache.
But ofcourse as earlier said we don't want to do it in a production box.
Also , this does not mean that applications will not be cached in memory any more . If we execute any application , the application will be loaded into the cache.

I tried executing the dd command to see the memory consumption. The following is the memory usage after terminating the dd command.

$ dd if=/dev/zero of=test
dd: writing to `test': No space left on device
2856305+0 records in
2856304+0 records out
1462427648 bytes (1.5 GB) copied, 25.7104 s, 56.9 MB/s
[
$ free -m
             total       used       free     shared    buffers     cached
Mem:          1987       1922         65          0          4       1670
-/+ buffers/cache:        247       1740
Swap:         1906          0       1906

We can see that the cache has again started filling up. So , from the above examples looks very much clear how we can release cache space by tuning the drop_cache parameter.

Comments

Popular Posts