设置/ proc / sys / vm / drop_caches清除缓存


79

作为一些冷缓存时间的一部分,我试图释放OS缓存。该内核文档(检索2019日)说:

drop_caches

Writing to this will cause the kernel to drop clean caches, as well as
reclaimable slab objects like dentries and inodes.  Once dropped, their
memory becomes free.

To free pagecache:
    echo 1 > /proc/sys/vm/drop_caches
To free reclaimable slab objects (includes dentries and inodes):
    echo 2 > /proc/sys/vm/drop_caches
To free slab objects and pagecache:
    echo 3 > /proc/sys/vm/drop_caches

This is a non-destructive operation and will not free any dirty objects.
To increase the number of objects freed by this operation, the user may run
`sync' prior to writing to /proc/sys/vm/drop_caches.  This will minimize the
number of dirty objects on the system and create more candidates to be
dropped.

This file is not a means to control the growth of the various kernel caches
(inodes, dentries, pagecache, etc...)  These objects are automatically
reclaimed by the kernel when memory is needed elsewhere on the system.

Use of this file can cause performance problems.  Since it discards cached
objects, it may cost a significant amount of I/O and CPU to recreate the
dropped objects, especially if they were under heavy use.  Because of this,
use outside of a testing or debugging environment is not recommended.

You may see informational messages in your kernel log when this file is
used:

    cat (1234): drop_caches: 3

These are informational only.  They do not mean that anything is wrong
with your system.  To disable them, echo 4 (bit 3) into drop_caches.

我对细节有些粗略。跑步

echo 3 > /proc/sys/vm/drop_caches

释放页面缓存,牙科和索引节点。好。

因此,如果我希望系统再次正常开始缓存,是否需要先将其重置为0?我的系统当前将值设置为0,我认为这是默认值。还是会自行重置?我在这里至少看到两种可能性,但我不确定哪一种是正确的:

  1. echo 3 > /proc/sys/vm/drop_caches释放页面缓存,牙科和索引节点。然后,系统立即再次开始缓存。我不确定在/proc/sys/vm/drop_caches这种情况下我期望该值做什么。几乎立即回到0?

  2. 如果/proc/sys/vm/drop_caches设置为3,则系统在重置为0之前不会进行任何内存缓存。

哪种情况是正确的?


22
搭配sudo一起使用:echo 3 | sudo tee /proc/sys/vm/drop_caches
Volker Siegel 2014年

天啊!@VolkerSiegel我已经擦洗了Interweb数小时,并随机找到了您的评论。尝试了一下,效果很好!感谢您添加此小技巧。我不想劫持这个问题,但是如果这不是不合适的话,我想请教一下。当我将sshpass与一起使用时sudo -i && echo 3 > /proc/sys/vm/drop_caches,出现错误:stdin: is not a tty。使用您的“ sudo”方法有效。为什么?
harperville '16

2
@harperville提出问题;这几乎可以肯定是一个不相关的问题。
Faheem Mitha

1
@harperville是的-这是一个很好的问题-有一个有趣的答案,请单独询问!那让我知道 还是您想让我自己问一个问题然后回答?
Volker Siegel

Answers:


106

它不是粘性的-您只需写入文件以使其失去缓存,然后立即开始再次缓存。

基本上,当您写入该文件时,您并没有真正更改设置,而是向内核发出命令。内核对该命令起作用(通过删除缓存),然后像以前一样进行。


2
好,谢谢。值会立即变回0吗?
Faheem Mitha

33
@FaheemMitha不,您可以读取的值是您最后输入的值,但它并没有在任何地方使用,只有编写动作很重要。源代码在中fs/drop_caches.c
吉尔斯

这样做对JVM有什么特别的好处?
JE卡特二世

3
相反,对于应用程序没有任何好处:文件加载速度会变慢,因为没有缓存的索引节点。另外,您内存也不低:如果应用程序需要内存,它将从操作系统缓存中获取。请参阅linuxatemyram.com
dr0i18年

@TomH,关于“仅书写作用”是sync命令?
kaizenCoder
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.