# 查询和清除文件系统缓存
Date: 2021-03-30


为了减少磁盘I/O，加快读写速度，Linux内核使用文件系统的Cache，Page Cache。

下面通过一个实验验证一下，查看Cache分配使用情况。

```
# free -w
total used free shared buffers cache available
Mem: 344756 106244 186612 1540 76 51824 226956
Swap: 2097148 30464 2066684
```

free 从/proc/meminfo 中获取信息进行展示，这里的Page Cache主要是 cache + buffers 这两个项目项目。

> page cache是针对 file systems ， buffer是针对 block devices 两者是在不同时期不同场景下涉及的缓存机制，kernel2.4版本之前是分开的，并存的。之后版本进行了融合。free默认不加-w参数，可以看到输出cache和buffer合计在一起

```
# dd if=/dev/random of=/root/data_file count=1400000

# du data_file -sh
103M data_file
```

使用读取两次文件观察下执行时间

```
# free -w
              total        used        free      shared     buffers       cache   available
Mem:         344756      106244      186612        1540          76       51824      226956
Swap:       2097148       30464     2066684
# time cat data_file > /dev/null

real    0m0.273s
user    0m0.000s
sys     0m0.064s
# free -w
              total        used        free      shared     buffers       cache   available
Mem:         344756      106240       81072        1540          76      157368      227012
Swap:       2097148       30464     2066684
# time cat data_file > /dev/null

real    0m0.031s
user    0m0.002s
sys     0m0.026s
```

可以看到第二次执行时间比第一次明显减少，清理一下page cache

```
# echo 1 > /proc/sys/vm/drop_caches

# free -w
              total        used        free      shared     buffers       cache   available
Mem:         344756      106228      186616        1544          76       51836      226976
Swap:       2097148       30464     2066684

# time cat data_file > /dev/null

real    0m0.292s
user    0m0.000s
sys     0m0.066s
```

cache空间被回收同时读取文件时间增加。

这里还要考虑到内存空间。 如果生成1G的文件读取：

```
# for i in `seq 1 10`; do echo $i; cat data_file >> large_file; done
# ls
data_file  large_file
# time cat large_file > /dev/null

real    0m3.884s
user    0m0.009s
sys     0m0.976s
# echo 1 > /proc/sys/vm/drop_caches
# time cat large_file > /dev/null

real    0m3.411s
user    0m0.008s
sys     0m0.850s

```

发现时间没有减少反而增加了，文件大于内存后，磁盘I/O交互就无法避免了，缓存效果就不明显了。

#### **参考及引用**

Photo by **[Sergei Akulich](https://www.pexels.com/@sergei-akulich-1322276?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels)** from **[Pexels](https://www.pexels.com/photo/body-of-water-under-gray-sky-2539438/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels)**

[How to Clear Cache on Linux](https://linuxhint.com/clear_cache_linux/)

