Friday, October 3, 2008

Flushing linux memory cache

I was looking for a fix to free the unused RAM in Linux. After searching for sometime and doing some research, I found this solution.

root@enjoyfast-lx:~# free -m
total used free shared buffers cached
Mem: 1002 984 18 0 89 386
-/+ buffers/cache: 508 494
Swap: 2047 0 2047
root@enjoyfast-lx:~# sync
root@enjoyfast-lx:~# echo 3 > /proc/sys/vm/drop_caches
root@enjoyfast-lx:~# free -m
total used free shared buffers cached
Mem: 1002 600 402 0 0 112
-/+ buffers/cache: 487 515
Swap: 2047 0 2047

root@enjoyfast-lx:~# echo 0 > /proc/sys/vm/drop_caches

The sync command will write the contents of cache into hard disk. But the cached pages will still remain in memory for quick access. This will actually speed up the execution of programs that are currently accessing this pages. But if you are running out of memory and need to free up some RAM, you can remove this pages from cache permanently bye changing the value of /proc/sys/vm/drop_caches to 3 . Now a quick analysis of what happens when we do this can be done by using the /proc/meminfo file.

Before running the above fix:

root@enjoyfast-lx:~/temp# cat /proc/meminfo > mem.b4

After running the fix

root@enjoyfast-lx:~/temp# cat /proc/meminfo > mem.af8r

root@enjoyfast-lx:~/temp# diff -y mem.b4 mem.af8r|tr -d '|'|awk '{ print $2"\t"$5"\t"expr $5 - $2"\t"$1 }'|awk '{if($3 != 0)print $0}'|sort -k4
474136 395276 -78860 Active:
346992 347096 104 AnonPages:
96172 452 -95720 Buffers:
396076 115380 -280696 Cached:
953836 954052 216 Committed_AS:
316 80 -236 Dirty:
1608 69064 67456 HighFree:
365060 67608 -297452 Inactive:
13992 342888 328896 LowFree:
15600 411952 396352 MemFree:
2928 2932 4 PageTables:
35480 15528 -19952 Slab:
25088 6308 -18780 SReclaimable:
10392 9220 -1172 SUnreclaim:

As you can see, its freeing up buffers and cache. For a complete reference of this values, go to:

http://www.redhat.com/advice/tips/meminfo.html

No comments:

Post a Comment