Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux Cache Memory 緩存機制深度解析:原理、監控與手動釋放

編輯:Linux 教學

Linux 會積極利用閒置記憶體作為頁面快取,這是效能優化的關鍵,而非記憶體洩漏。本文解析 /proc/meminfo 與 free 輸出含義,釐清「可用記憶體」真相,並提供安全的手動釋放指令。

核心觀念:Cache = 免費加速器

  • 讀寫檔案時,核心將資料暫存於記憶體,下次存取直接命中,避免磁碟 I/O
  • 應用程式需要記憶體時,核心會**自動**回收 Cache,零延遲、零風險
  • 免費記憶體 = 浪費記憶體,高 Cache 使用率代表系統健康

解讀 /proc/meminfo 關鍵欄位

MemTotal:       16425996 kB  # 總物理記憶體
MemFree:         5698808 kB  # 完全未使用
Buffers:          380904 kB  # 區塊裝置元資料快取(inode、目錄等)
Cached:          9389356 kB  # 頁面快取(檔案內容)
SwapCached:          212 kB  # 曾寫入 Swap 又讀回的頁面
Active:          6569200 kB  # 近期使用的頁面
Inactive:        3725364 kB  # 待回收頁面

free 指令三行輸出完整解碼

              total        used        free      shared  buff/cache   available
Mem:        16425996    10727220     5698776           0      9770124    15469512
Swap:        8273464         212     8273252
欄位含義
total物理記憶體總量
used已配置給應用 + buff/cache(非真實佔用)
free完全閒置(通常很小)
buff/cacheBuffers + Cached,核心可隨時回收
available真實可給新程式用的記憶體 = free + 可回收 cache

公式:
used = total - free - buff/cache
available ≈ free + buffers + cached

手動釋放 Cache(極少數場景才需)

# 釋放前先同步,防止資料遺失
sync

# 1. 僅釋放頁面快取
echo 1 > /proc/sys/vm/drop_caches

# 2. 釋放 dentries 與 inodes
echo 2 > /proc/sys/vm/drop_caches

# 3. 全部釋放(頁面快取 + dentries + inodes)
echo 3 > /proc/sys/vm/drop_caches

警告:生產環境**強烈不建議**定時釋放。會導致後續檔案存取必須重新讀磁碟,效能驟降。僅適用於基準測試前校準、記憶體洩漏排查等特殊場景。

監控腳本範例

#!/bin/bash
# 每 10 秒記錄 available 記憶體
watch -n 10 "free -h | awk '/Mem:/ {print \$7}'"

Linux 記憶體管理哲學:信任核心。高 Cache 不是問題,低 available 才是隱憂。讓核心自動平衡,才是最高效的調優。

Copyright © Windows教程網 All Rights Reserved