天天看點

關于linux作業系統中的buff/cache

作者:流火星空26131197

一 背景

如圖,當我們檢視記憶體資訊時,通常會使用vmstat或free指令。在使用vmstat -S M時,會看到下面的結果。

關于linux作業系統中的buff/cache

使用free -m指令檢視記憶體資訊:

關于linux作業系統中的buff/cache

在這裡,我們能夠看到記憶體資訊中包含了swpd, free, buff, cache等等。其中,最熟悉和分析最多的就是buff 和 cache。通常,我們都有簡單的了解,例如buffer是緩沖區,cache是緩存;通常操作時是讀cache,寫buffer等等,但深入一點,這二者的差别是什麼呢?本章将結合stackoverflow上的一個問題及回答進行分析。

二 解答

2.1 根據以往資料整理的了解

1、Buffer(緩沖區)是系統兩端處理速度平衡(從長時間尺度上看)時使用的。它的引入是為了減小短期内突發I/O的影響,起到流量整形的作用。比如生産者——消費者問題,他們産生和消耗資源的速度大體接近,加一個buffer可以抵消掉資源剛産生/消耗時的突然變化。

2、Cache(緩存)則是系統兩端處理速度不比對時的一種折衷政策。因為CPU和memory之間的速度差異越來越大,是以人們充分利用資料的局部性(locality)特征,通過使用存儲系統分級(memory hierarchy)的政策來減小這種差異帶來的影響。

3、假定以後存儲器通路變得跟CPU做計算一樣快,cache就可以消失,但是buffer依然存在。比如從網絡上下載下傳東西,瞬時速率可能會有較大變化,但從長期來看卻是穩定的,這樣就能通過引入一個buffer使得OS接收資料的速率更穩定,進一步減少對磁盤的傷害。

2.2 stackoverflow的回答

原問題:https://stackoverflow.com/questions/6345020/what-is-the-difference-between-buffer-and-cache-memory-in-linux

Linux中,buff和cache 記憶體有什麼差別?

Short answer: Cached is the size of the page cache. Buffers is the size of in-memory block I/O buffers. Cached matters; Buffers is largely irrelevant.

Long answer: Cached is the size of the Linux page cache, minus the memory in the swap cache, which is represented by SwapCached (thus the total page cache size is Cached + SwapCached). Linux performs all file I/O through the page cache. Writes are implemented as simply marking as dirty the corresponding pages in the page cache; the flusher threads then periodically write back to disk any dirty pages. Reads are implemented by returning the data from the page cache; if the data is not yet in the cache, it is first populated. On a modern Linux system, Cached can easily be several gigabytes. It will shrink only in response to memory pressure. The system will purge the page cache along with swapping data out to disk to make available more memory as needed.

Buffers are in-memory block I/O buffers. They are relatively short-lived. Prior to Linux kernel version 2.4, Linux had separate page and buffer caches. Since 2.4, the page and buffer cache are unified and Buffers is raw disk blocks not represented in the page cache—i.e., not file data. The Buffers metric is thus of minimal importance. On most systems, Buffers is often only tens of megabytes.

翻譯過來:

簡短回答:Cached是頁緩存(page cache)的大小;而Buffers是記憶體塊I/O緩沖區的大小。Cache很重要,而Buffers沒那麼重要。

詳細回答:Cached是Linux頁緩存的大小減去swap cache(交換區)中記憶體的大小——SwapCached(全部頁緩存大小等于Cached+SwapCached)。Linux通過頁緩存來執行所有檔案I/O操作。寫操作隻是簡單地将頁緩存中的相應頁标記為髒頁。讀操作是通過傳回頁緩存中的資料來實作的;如果資料還沒有在緩存中,會先添加。在現在的Linux作業系統中,Cached很容易達到GB級别,它隻會在記憶體面臨壓力時縮小。系統将清除頁面緩存,同時将記憶體中的資料交換到磁盤,以便在需要時提供更多可用記憶體。

Buffers(緩沖區)是記憶體塊 I/O 緩沖區,生命周期相對較短。在Linux核心版本2.4之前,Linux有獨立的頁緩存和緩沖區緩存。從2.4版本開始,頁緩存和緩沖區緩存統一,緩沖區是未展現在頁緩存中的原始(裸)磁盤塊——也就是說,不是檔案資料。是以緩沖區的大小并不重要,在大部分系統中,緩沖區通常隻有幾十M位元組。

2.3 關于髒頁

Linux 以頁作為高速緩存的機關,當程序修改了高速緩存中的資料時,該頁就會被核心标記為髒頁,核心會在合适的時間把髒頁的資料刷寫到磁盤中去,以保持高速緩存中的資料與磁盤中的資料是一緻的.

繼續閱讀