Tuesday, May 22, 2012

How to Release the Linux Disk Buffer/Cache

Linux like most modern OS will always try to use free RAM for caching stuff.  For performance benchmarks, we recommend you to release the Linux disk buffer/cache before each test for more meaningful comparisons.  This step is necessary.  For example, in the first run of your application, Linux could load the files your application use into the buffer cache and leave them there; thus subsequent runs of the same application could run faster.

In this article, we will show you:
  1. How to check your disk buffer and cache usage before and after releasing them?
  2. How to release disk buffer and cache?

How to Check

To check the disk buffer and cache usage, you can use Linux free command or read /proc/meminfo file.  For example, here is the disk buffer and cache usage before their release:

$ free -k
             total       used       free     shared    buffers     cached
Mem:      11790008   10241024    1548984          0     833088    8391724
-/+ buffers/cache:    1016212   10773796
Swap:      8191968          0    8191968


With "-k" option above, the space is displayed in KB.  For example, the system has total 11 GB with 9 GB used and 1GB free.  In the used space, it also counts the space used by disk buffers and caches.  The second row in the display (i.e., "-/+ buffers/cache") shows the space when ignoring buffers and caches.  For example, after counting buffers (i.e., 813MB) and caches (i.e., 8 GB) as free, the total free space becomes:
  • 10773796 KB =  1548984 KB +  833088 KB +  8391724 KB
When memory gets scarce, buffers and caches will be freed automatically.  So, they can be counted as free space.

How to Release

To release disk buffers and caches used by the kernel, you need to be "root".  Then the following one line command can do the work:

# sync && echo 3 > /proc/sys/vm/drop_caches

First we run the sync command before dropping the cache. Doing this will ensure that all memory in the cache is updated and all dirty pages are synchronized before dropping the cache.  The next step is echoing “3″ to the /proc/sys/vm/drop_caches file which will signal the kernel to release the pagecache, dentries and inodes.

After the commands, we can see some buffers and caches have been released by the kernel:

# free -k
             total       used       free     shared    buffers     cached
Mem:      11790008    6692304    5097704          0        940    5949888
-/+ buffers/cache:     741476   11048532
Swap:      8191968          0    8191968

Note that free command displays amount of free and used memory in the system by reading /proc/meminfo file.  So, you can find the same information from that file.

References

2 comments:

zivag said...

Thanks, helpful!

Blogger said...

QUANTUM BINARY SIGNALS

Get professional trading signals sent to your mobile phone daily.

Start following our signals right now and make up to 270% per day.