Linux Buffer/Cache 的区别

时间:2023-03-09 09:34:25
Linux Buffer/Cache 的区别

  以前经常使用free -h命令来查看当前操作系统的内存使用情况,同时也注意过返回信息中有一列是buff/cache,来公司之前,面试官还问过我这两个的区别,当时没有回答出来,现在特意回顾记录下:

free -h

              total        used        free      shared  buff/cache   available
Mem: 3.7G 2.0G 318M 41M 1.4G 1.3G
Swap: 2.0G 87M 1.9G

区别

  • A buffer is someting that has yet to be 'written' to disk.
  • A cache is someting that has been 'read' from the disk and stored for later use.

  buffer用于存放输入到磁盘上的数据,而cache是从磁盘中读出数据存储在内存中待以后进行使用。

测试

  1. 生成一个测试文件。

Linux Buffer/Cache 的区别

  1. 清空缓存

Linux Buffer/Cache 的区别

三种清空方式:

  • echo 1 > /proc/sys/vm/drop_caches:仅清除页面缓存
  • echo 2 > /proc/sys/vm/drop_caches:清除目录项和inode
  • echo 3 > /proc/sys/vm/drop_caches:清除页面缓存、目录项以及inode
  1. 读取测试文件,查看读取时长

Linux Buffer/Cache 的区别

  我们可以看到,读取时长在52s,第一次读取文件后,已经写入cache。

  1. 测试第二次读取文件时长

Linux Buffer/Cache 的区别

  当我们清除cache后读取此测试文件时长为52s,当第一次读取完成后写入cache再次读取时,时长为0.24s,性能可谓极大提升。

  测试时可能遇到的关于time命令的坑,我们系统中是自带time命令的,不过并不常用,我们用于测试使用的time是需要单独安装的:yum -y install time。可以使用以下方法进行区分:

which time

/usr/bin/which: no time in (/usr/lib64/qt-3.3/bin:/root/perl5/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)

  给我们上述返回值时,表示我们的time命令还没有安装。

type time

time is a shell keyword

  返回time是一个shell关键字同样不是我们想要的time命令。

time --version

zsh: command not found: --version
--version 0.00s user 0.00s system 60% cpu 0.001 total

  查看time版本提示命令未安装,表示我们需要使用的time命令还没有被安装。

yum -y install time

which time

/usr/bin/time

/usr/bin/time --version

GNU time 1.7

  有上述信息,我们就可以开始使用啦。