天天看點

Tips for Optimization Linux Memory Usage

記憶體洩露的檢視與檢測:

Linux Free 指令的輸出:

                total          used           free                 shared    buffers     cached

Mem:       8298904    6202940    2095964          0             400124    5291536

-/+ buffers/cache:     511280    7787624

Swap:      2048276    0               2048276

buffers 和 cached 主要是為了提高磁盤的讀取效率,除了對dentry進行緩存外,還采取了兩種cache方式:Buffer Cache和Page Cache,前者主要針對磁盤塊的讀寫,後者主要針對inode的讀寫;

buffers 主要指Buffer Cache,cached 主要指Page Cache。

-/+ buffers/cache: 意思是減去(buffers + cached)後真正地記憶體使用量,和加上(buffers + cached)後真正地記憶體空閑量。

used數值包括了進城所使用的記憶體和一部分磁盤緩存;

那used的數值比較異常,是發生了記憶體洩露嗎?非也!!

Usually the kernel handles memory utilization pretty well it caches memory for dentry cache, page cache and inodes which improves IO speed and performance generally. But in some cases user applications needs lots of memory and we need to clear what’s called dirty memory which could be inodes already written to the disk, so now the kernel given us the option to manage this manually. Used memory 幾乎總是會包含磁盤緩存,是以檔案讀寫過多之後導緻可用記憶體就會急劇下降,其他應用需要記憶體的時候就會發生disk buffer的sync操作,以至于系統性能大受影響。

Linux Kernel提供了有效地方法來清除磁盤緩存:/proc/sys/vm/drop_caches (具體在哪個版本後的kernel才支援,尚未查閱)

        echo 1 > /proc/sys/vm/drop_caches  free page cache

        echo 2 > /proc/sys/vm/drop_caches  free dentry and inodes cache

        echo 3 > /proc/sys/vm/drop_caches  free both of the two above

在執行這些操作之前,最好先執行sync (flush file system buffers)

Linux principals:

When extra physical memory is not in use, the kernel attempts to put it to work as a disk buffer cache. The disk buffer stores recently accessed disk data in memory; if the same data is needed again it can be quickly retrieved from the cache, improving performance. The buffer grows and shrinks dynamically to use the memory available, although priority is given to using the memory for paging. Thus, all the memory you have is put to good use.

繼續閱讀