Как очистить кэш в linux
Перейти к содержимому

Как очистить кэш в linux

  • автор:

How to Clear Cache on Linux

The kernel reserves a certain amount of system memory for caching the file system disk accesses in order to make overall performance faster. The cache in linux is called the Page Cache. The size of the page cache is configurable with generous defaults enabled to cache large amounts of disk blocks. The max size of the cache and the policies of when to evict data from the cache are adjustable with kernel parameters. The linux cache approach is called a write-back cache. This means if data is written to disk it is written to memory into the cache and marked as dirty in the cache until it is synchronized to disk. The kernel maintains internal data structures to optimize which data to evict from cache when more space is needed in the cache.

During Linux read system calls, the kernel will check if the data requested is stored in blocks of data in the cache, that would be a successful cache hit and the data will be returned from the cache without doing any IO to the disk system. For a cache miss the data will be fetched from IO system and the cache updated based on the caching policies as this same data is likely to be requested again.

When certain thresholds of memory usage are reached background tasks will start writing dirty data to disk to ensure it is clearing the memory cache. These can have an impact on performance of memory and CPU intensive applications and require tuning by administrators and or developers.

Using Free command to view Cache Usage

We can use the free command from the command line in order to analyze the system memory and the amount of memory allocated to caching. See command below:

What we see from the free command above is that there is 7.5 GB of RAM on this system. Of this only 209 MB is used and 6.5 MB is free. 667 MB is used in the buffer cache. Now let’s try to increase that number by running a command to generate a file of 1 Gigabyte and reading the file. The command below will generate approximately 100MB of random data and then append 10 copies of the file together into one large_file.

Now we will make sure to read this 1 Gig file and then check the free command again:

We can see the buffer cache usage has gone up from 667 to 1735 Megabytes a roughly 1 Gigabyte increase in the usage of the buffer cache.

Proc Sys VM Drop Caches Command

The linux kernel provides an interface to drop the cache let’s try out these commands and see the impact on the free setting.

We can see above that the majority of the buffer cache allocation was freed with this command.

Experimental Verification that Drop Caches Works

Can we do a performance validation of using the cache to read the file? Let’s read the file and write it back to /dev/null in order to test how long it takes to read the file from disk. We will time it with the time command. We do this command immediately after clearing the cache with the commands above.

It took 8.4 seconds to read the file. Let’s read it again now that the file should be in the filesystem cache and see how long it takes now.

Boom! It took only .2 seconds compared to 8.4 seconds to read it when the file was not cached. To verify let’s repeat this again by first clearing the cache and then reading the file 2 times.

It worked perfectly as expected. 8.5 seconds for the non-cached read and .2 seconds for the cached read.

Conclusion

The page cache is automatically enabled on Linux systems and will transparently make IO faster by storing recently used data in the cache. If you want to manually clear the cache that can be done easily by sending an echo command to the /proc filesystem indicating to the kernel to drop the cache and free the memory used for the cache. The instructions for running the command were shown above in this article and the experimental validation of the cache behavior before and after flushing were also shown.

About the author

Linux Wolfman

Linux Wolfman is interested in Operating Systems, File Systems, Databases and Analytics and always watching for new technologies and trends. Reach me by tweeting to @linuxhint and ask for the Wolfman.

Как освободить память Linux

Как и любая другая операционная система, Linux очень эффективно работает с оперативной памятью. Доступная память свободно распространяется между процессами, неиспользуемые страницы сбрасываются в раздел подкачки на диске, а в случае переполнения памяти, срабатывает специальный механизм, встроенный в ядро, который анализирует все процессы и уничтожает виновника.

Когда любой процесс пишет данные на диск, они сохраняются ядром в отдельном кэше. Очень часто этот кэш занимает достаточно много места. В этой статье мы рассмотрим как освободить память в Linux, а точнее, как очистить созданный программами кэш, а также как вычислить и завершить процессы, которые потребляют больше всего памяти.

Как освободить кэш память в Linux

В каждом дистрибутиве Linux можно использовать три команды чтобы очистить кэш памяти linux. Причем вам не придется завершать никаких процессов. Сначала войдите в консоль от имени суперпользователя:

Затем выполните одну из команд. Очистка кэша PageCache:

sync; echo 1 > /proc/sys/vm/drop_caches

Очистка inode и dentrie:

sync; echo 2 > /proc/sys/vm/drop_caches

Очистка inode и dentrie и PageCache:

sync; echo 3 > /proc/sys/vm/drop_caches

А теперь давайте рассмотрим что происходит при выполнении этих команд.

Утилита sync заставляет систему записать все кэшированные, но еще не записанные данные на диск. Это нужно чтобы освободить как можно больше памяти. По умолчанию данные после записи на диск не удаляются из кэша, это нужно для того, чтобы программа могла быстрее их считать при необходимости.

Если не выполнить команду sync мы тоже освободим немного места, но после ее выполнения результат будет лучше.

Символ разделения ; дает знать оболочке, что перед тем как выполнить другую команду, нужно дождаться завершения работы первой. Последняя команда echo 1 > /proc/sys/vm/drop_caches записывает значение 1 в файл /proc/sys/vm/drop_caches. Это дает сигнал ядру, что нужно очистить выбранный нами вид кэша.

Виды кэша в Linux

А теперь давайте рассмотрим виды кэша, которые позволяют очищать эти команды, а также как все это работает.

PageCache или страничный кэш — это место, куда ядро складывает все данные, которые вы записывали или читали из диска. Это очень сильно ускоряет работу системы, так как если программе во второй раз понадобятся те же данные, они просто будут взяты из оперативной памяти. Но по этой причине этот кэш занимает больше всего места.

Посмотреть размер страничного кэша можно с помощью утилиты free. Здесь он показан в последней колонке — cached:

cache

Такой кэш чистить эффективнее и безопаснее всего.

Кэш inode и dentrie тоже относится к файловой системе. Только в него записываются не сами данные, а структура файловой системы, расположение файлов и папок. При запросе расположения файла или содержимого папки ядро формирует специальные структуры, в которых есть вся эта информация. При следующем запросе структуры будут уже сохранены в памяти. Для каждой файловой системы существует свой кэш inode и общий кэш dentrie.

Этот кэш занимает очень мало памяти. Данные представлены в байтах, и как видите, это очень мало. Посмотреть его можно командой:

cat /proc/slabinfo | egrep dentry\|inode

cache2

Очищать его чтобы освободить память linux не рекомендуется, так как памяти потребляется немного, а на новое сканирование файловой системы идет относительно много времени.

Нужно ли очищать кэш вообще?

Во-первых, если занято очень много памяти, вы можете очистить страничный кэш, особенно если это он занимает много памяти. Во-вторых, очистить кэш памяти linux может понадобиться, если вы изменяли какие-либо настройки файловой системы или ядра, а теперь хотите проверить как это отразилось на скорости операций чтения/записи. В таком случае можно очистить все кэши и сделать это без перезагрузки, что очень удобно.

Операционная система Linux разработана таким образом, что перед тем как обратиться к диску, будет просмотрен кэш диска, и если там есть нужные данные, к диску обращений не будет. Если очистить кэш Linux то операционная система будет работать немного медленнее, поскольку ей придется искать данные на диске.

Автоматическая очистка кэша

Давайте рассмотрим как автоматически очистить кэш памяти ежедневно в два часа ночи с помощью планировщика заданий cron.

Сначала создадим bash скрипт со следующим содержимым:

sudo vi /usr/local/bin/clearcache.sh

#!/bin/bash
sync ; echo 1 > /proc/sys/vm/drop_caches

Очищать будем только страничный кэш, так как он занимает больше всего. Другие виды трогать не будем, чтобы зря не понижать производительность системы.

Дальше сделайте скрипт исполняемым:

sudo chmod 755 /usr/local/bin/clearcache.sh

Осталось добавить задание в планировщик cron. Для этого выполните команду:

И в открывшемся редакторе добавьте строчку:

0 2 * * * /usr/local/bin/clearcache.sh

Теперь этот скрипт будет выполняться каждую ночь и выполнять очистку памяти, чтобы сервер мог работать нормально.

Настройка размера кэша памяти

Куда удобнее не очищать кэш каждый раз, а настроить ограничение, при превышении которого система сама будет удалять лишние страницы. Вы не можете явно ограничить сколько мегабайт может система использовать под кэш. Будет использоваться вся доступная память по мере необходимости, но можно настроить скорость удаления просроченных страниц из кэша.

За это отвечает файл /proc/sys/vm/vfs_cache_pressure. Он содержит относительный показатель, насколько агрессивно нужно удалять страницы из кэша. По умолчанию установлен параметр 100. Если его уменьшить ядро будет реже удалять страницы и это приведет к очень быстрому увеличению кэша. При нуле страницы вообще не будут удаляться. Если значение больше 100, размер кэша будет увеличиваться медленнее и неиспользуемые страницы будут сразу удаляться.

Например, сделаем минимальный размер кэша:

echo 1000 > /proc/sys/vm/vfs_cache_pressure

Не забудьте, что это очень сильно снизит производительность вашей системы, потому что вместо кэша данные будут читаться из диска.

Как очистить память подкачки

Пространство подкачки очистить очень просто. Для этого выполните:

swapoff -a && swapon -a

Имейте в виду, что при очистке swap, все данные будут перенесены обратно в оперативную память.

Как освободить память занимаемую процессами

Если в вашей системе нет памяти и кэш здесь ни при чём, следует завершить несколько процессов, потребляющих больше всего памяти. Для этого сначала надо вычислить такие процессы. Чтобы это сделать можно воспользоваться утилитой ps:

ps -e -o pid,user,%mem,command —sort %mem

Как видите, больше всего здесь памяти занимает chromium. Теперь вам надо его завершить. Идентификатор процесса, по которому его можно завершить отображается в первой колонке. Поэтому:

Более подробно о том как завершить процесс читайте в этой статье. Таким образом, вы можете освободить память от процессов, которые занимают больше всего памяти, а потом уже настроить zram или swap для того, чтобы память не переполнялась.

Выводы

Вот и все. Вы уже знаете очистить кэш linux и освободить память. Не забудьте, что все команды, приведенные в этой статье нужно выполнять от имени суперпользователя, иначе ничего работать не будет. Если остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

How to clear memory cache in Linux [duplicate]

TOP

Is there any command that by using I can clean the cache in RHEL?

I used this command:

but it didn’t work.

polym's user avatar

2 Answers 2

Depending on what you want to do you can use 1,2 or 3

Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.

To free pagecache:

To free dentries and inodes:

To free pagecache, dentries and inodes:

As this is a non-destructive operation and dirty objects are not freeable, the user should run ‘sync’ first.

How To Clear .Cache Folders and Free Up Space On Your Linux PC

Kirtipurohit

GNU/Linux has implemented efficient storage management for its users. But have you noticed your Linux system running out of space, filled with unused packages you installed months or years ago? How do find them and remove them? Here are a few valuable tips!

Cache File Location

Cache files are stored in /home/username/.cache which mostly consists of your browser’s data, IDE’s (if you use any ) and other software. Each user has its own data and this can build up exponentially . In order to clear it all it’s recommended to have Disk usage analyzer installed.

Disk Usage Analyzer

Disk Usage Analyzer, formerly known as Baobab, is a graphical disk usage analyzer for the GNOME desktop environment. It was part of gnome-utils, but has been a standalone application since GNOME 3.4.

The software gives the user a graphical representation of a disk drive’s contents. The interface allows for selection of specific parts of filesystem so a single folder, the entire filesystem, and even remote folders and filesystems can be scanned and listed at the folder level.

The graphical representation can be switched between a ‘Rings’ chart and a ‘Treemap’ chart to better suit the content being viewed.

Installation

If you don’t already have Disk Usage Analyzer installed, you first need to install the baobab package:

On Ubuntu

On Debian

On Arch Linux

Fedora

On OpenSUSE

Clear Cache files and folders

Step 1:

Click on home for your user data .

Click on your second disk i.e Vostro-14-3468 as shown in the image below .

Note: Names will be different on your own computer.

Here, the other disks shown as New Volume / 262 GB volume are formatted disks for a dual boot system, in my case Ubuntu 20.10 and Windows 10.

Step 2:

As you click on it, the Disk Usage Analyzer will start to scan your directory for files and folders. Be patient and allow it to finish. After Disk Usage Analyzer is done scanning your Linux PC for files it shows the live illustration of Linux disk usage as the form of a pie chart.

To see updated changes in your filesystem, you’ll need to refresh the scan as it won’t track these storage changes “live.”

Look in the folder tree structure for .cache, and click on it .

Step 3:

Once you click on the .cache folder, the disk usage analyzer will show you the space it’s consuming graphically on the right side .

  • Find the sub folders inside it which you wish to delete .
  • Right-click each one
  • Select Move to trash / bin
  • Now empty your trash / bin

And you are done!

Do not worry about deleting these folders. It is totally safe and the software will recreate them if and when it needs to.

WARNING!

Do not delete anything from your usr and var directories. usr is used for “user programs”. Usually your package manager installs all the binaries, shared files etc. from all programs here (except config files, which go to /etc).

You can check /usr/bin for binaries, /usr/share for shared files (media, etc), /usr/share/doc for documentation.

There is also an /opt folder, where there are “other” binary programs or programs installed from sources other than the default package manager. Some programs like that (usually compiled) also go to usr/local

/var is usually used for log files, ‘temporary’ files (like mail spool, printer spool, etc), databases, and all other data not tied to a specific user.

Logs are usually in /var/log databases in var/lib (mysql — var/lib/mysql ), etc.

If you liked this article, please follow the author on medium!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *