Как узнать оперативную память linux

Введение

О природе swap’а

Во время инициализации долго выполняющаяся программа может выделить и использовать многие страницы. Эти же страницы могут использоваться в процессе завершения работы/очистки, но не требуются после «старта» (в понимании самого приложения) программы. Довольно распространённое явление для демонов, использующих крупные зависимости для инициализации.
Во время нормальной работы программы мы можем выделить память, которая затем редко используется

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

CPU

Overclocking

Overclocking improves the computational performance of the CPU by increasing its peak clock frequency. The ability to overclock depends on the combination of CPU model and motherboard model. It is most frequently done through the BIOS. Overclocking also has disadvantages and risks. It is neither recommended nor discouraged here.

Many Intel chips will not correctly report their clock frequency to acpi_cpufreq and most other utilities. This will result in excessive messages in dmesg, which can be avoided by unloading and blacklisting the kernel module .
To read their clock speed use i7z from the package. To check for correct operation of an overclocked CPU, it is recommended to do stress testing.

Alternative CPU schedulers

This article or section needs expansion.

The default CPU scheduler in the mainline Linux kernel is CFS. Alternative schedulers are available.

Real-time kernel

Some applications such as running a TV tuner card at full HD resolution (1080p) may benefit from using a realtime kernel.

See also and .

Cpulimit

$ cpulimit -l 50 -p 5081

irqbalance

The purpose of is distribute hardware interrupts across processors on a multiprocessor system in order to increase performance. It can be by the provided .

Turn off CPU exploit mitigations

Turning off CPU exploit mitigations improves performance (sometimes up to 50%). Use below kernel parameter to disable them all:

mitigations=off

zram 技术的由来

zram(也称为 zRAM,先前称为 compcache)是 Linux 内核的一项功能,可提供虚拟内存压缩。zram 通过在 RAM 内的压缩块设备上分页,直到必须使用硬盘上的交换空间,以避免在磁盘上进行分页,从而提高性能。由于 zram 可以用内存替代硬盘为系统提供交换空间的功能,zram 可以在需要交换 / 分页时让 Linux 更好利用 RAM ,在物理内存较少的旧电脑上尤其如此。

即使 RAM 的价格相对较低,zram 仍有利于嵌入式设备、上网本和其它相似的低端硬件设备。这些设备通常使用固态存储,它们由于其固有性质而寿命有限,因而避免以其提供交换空间可防止其迅速磨损。此外,使用 zRAM 还可显著降低 Linux 系统用于交换的 I/O 。

zram 在 2009 年的时候就进了 kernel 的 staging 目录,并于 2014 年 3 月 30 日发布的 3.14 版本正式合并入 Linux 内核主线。在 2014 年 6 月 8 日发布的 3.15 版本的 Linux 内核中,zram 已可支持 LZ4 压缩算法,而 LZO 仍然作为默认的压缩后端。内核 3.15 中的修改还改进了性能,以及经由 sysfs 切换压缩算法的能力。

Lubuntu 于 13.10 开始使用 zram 。截至 2012 年 12 月,Ubuntu 考虑为小内存的计算机默认启用 zram 。 Google 在 Chrome OS 中使用 zram,它也成为了 Android 4.4 及以后版本设备的一个选项。

本文主要介绍在 Android 设备上使用的 zram swap,它可以让小内存的设备在多任务的情况下切换自如,提高用户体验。

zram swap 主要原理就是从内存分配一块区域出来用作 swap 分区,每次如果内存空间不够了,不是把应用程序杀掉,而是把应用程序所占用的内存数据复制到 swap 分区,等切换回来的时候就可以直接把这部分数据恢复到内存当中,节省重新开启所需的时间。而被放到 swap 分区的应用程序,所占用的内存都是被压缩过的,比如,微信在普通内存中占用 50 MB 的空间,如果压缩率为 0.4,则放到 swap 分区里面的数据只需要 20 MB 的空间,这样 swap 分区里面就可以存放更多后台临时不用的应用程序,变相扩展了内存的大小。

Раздел подкачки в оперативной памяти

Раньше эта мысль вызвала бы непонимание или насмешки в сторону человека, её продвигающую. Однако времена поменялись.
Итак, представим. У вас компьютер с небольшим объемом памяти, 512 мб или 1024 мб. В принципе для повседневной работы Linux-based операционных систем этого хватит, но и здесь бывают случаи, когда памяти надо гораздо больше, например для сборки некоторых пакетов может понадобится 8гб памяти. Для этого и существует такое явление, как раздел подкачки, он же swap. Вроде всё прекрасно и из ситуации вышли, но скорость записи/чтения у жестких дисков на несколько порядков ниже, чем у оперативной памяти. Даже пускай вы используете быстрые твердотельные накопители SSD (на которых swap размещать вообще не советуют, кстати), то и они значительно уступают оперативной памяти по скорости.
А теперь развиваем мысль и подключаем модуль ядра zRam и размещаем на созданном виртуальном блочном устройстве раздел подкачки. Скорость работы с этими данными будут несколько ниже, чем напрямую с памятью из-за сжатия их, однако всё же никакой жесткий диск или твердотельный накопитель не сможет сравниться. Да и нагрузку на последние снимем таким способом.

Что же у нас получается? Если памяти вдруг перестает хватать, компьютер будет сжимать «блоки» памяти и размещать опять таки в памяти. Звучит красиво, а главное в наши дни это реально.
Что нам это даст? Бесплатное «увеличение» оперативной памяти на серверах, уменьшение нагрузки на жесткий диск и твердотельные накопители. Последнее особенно актуально на нетбуках — памяти там обычно кот наплакал, а увеличить не всегда возможно.

Description

zram-config — Upstart job to enable zram support

Property Value
Operating system Linux
Distribution Ubuntu 18.04 LTS (Bionic Beaver)
Repository Ubuntu Universe amd64
Official
Package filename zram-config_0.5_all.deb
Package name zram-config
Package version 0.5
Package release
Package architecture all
Package type deb
Homepage
License
Maintainer Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Download size 4.21 KB
Installed size 54.00 KB
Category universe/utils
This installs a simple Upstart job to enable zram support
on kernels that have the module available.

Скорость битов

полосой пропускания (bandwidth)теоретическая
адрес строкиpre-chargingтаймингами памятизадержками

Название тайминга Описание Обычное значение в DDR4
tRCD Row-to-Column Delay: количество циклов между активацией строки и возможностью выбора столбца 17 циклов
CL CAS Latency: количество циклов между адресацией столбца и началом передачи пакет данных 15 циклов
tRAS Row Cycle Time: наименьшее количество циклов, в течение которого строка должна оставаться активной перед тем, как можно будет выполнить её pre-charging 35 циклов
tRP Row Precharge time: минимальное количество циклов, необходимое между активациями разных строк 17 циклов

намногоДаже памяти нужна память. Красным указано ПЗУ (read-only memory, ROM), в котором содержится информация SPD.serial presence detect«Я могу работать с вот с такими нестандартными таймингами»

Watchdogs

According to Wikipedia:Watchdog timer:

A watchdog timer is an electronic timer that is used to detect and recover from computer malfunctions. During normal operation, the computer regularly resets the watchdog timer . If, , the computer fails to reset the watchdog, the timer will elapse and generate a timeout signal used to initiate corrective actions typically include placing the computer system in a safe state and restoring normal system operation.

Many users need this feature due to their system’s mission-critical role (i.e. servers), or because of the lack of power reset (i.e. embedded devices). Thus, this feature is required for a good operation in some situations. On the other hand, normal users (i.e. desktop and laptop) do not need this feature and can disable it.

To disable watchdog timers (both software and hardware), append to your boot parameters.

To check the new configuration do:

# cat /proc/sys/kernel/watchdog

or use:

# wdctl

After you disabled watchdogs, you can optionally avoid the loading of the module responsible of the hardware watchdog, too. Do it by blacklisting the related module, e.g. .

Either action will speed up your boot and shutdown, because one less module is loaded. Additionally disabling watchdog timers increases performance and .

RAM, swap and OOM handling

Clock frequency and timings

RAM can run at different clock frequencies and timings, which can be configured in the BIOS. Memory performance depends on both values. Selecting the highest preset presented by the BIOS usually improves the performance over the default setting. Note that increasing the frequency to values not supported by both motherboard and RAM vendor is overclocking, and similar risks and disadvantages apply, see .

Root on RAM overlay

If running off a slow writing medium (USB, spinning HDDs) and storage requirements are low, the root may be run on a RAM overlay ontop of read only root (on disk). This can vastly improve performance at the cost of a limited writable space to root. See AUR.

Zram or zswap

Similar benefits (at similar costs) can be achieved using zswap rather than zram. The two are generally similar in intent although not operation: zswap operates as a compressed RAM cache and neither requires (nor permits) extensive userspace configuration.

Example: To set up one lz4 compressed zram device with 32GiB capacity and a higher-than-normal priority (only for the current session):

# modprobe zram
# echo lz4 > /sys/block/zram0/comp_algorithm
# echo 32G > /sys/block/zram0/disksize
# mkswap --label zram0 /dev/zram0
# swapon --priority 100 /dev/zram0

To disable it again, either reboot or run

# swapoff /dev/zram0
# rmmod zram

The package provides a unit to automatically initialize zram devices. Configuration is possible in .

The package AUR provides an automated script for setting up a swap with a higher priority and a default size of 20% of the RAM size of your system. To do this automatically on every boot, enable .

Swap on zRAM using a udev rule

The example below describes how to set up swap on zRAM automatically at boot with a single udev rule. No extra package should be needed to make this work.

First, enable the module:

/etc/modules-load.d/zram.conf
zram

Configure the number of /dev/zram nodes you need.

/etc/modprobe.d/zram.conf
options zram num_devices=2

Create the udev rule as shown in the example.

/etc/udev/rules.d/99-zram.rules
KERNEL=="zram0", ATTR{disksize}="512M" RUN="/usr/bin/mkswap /dev/zram0", TAG+="systemd"
KERNEL=="zram1", ATTR{disksize}="512M" RUN="/usr/bin/mkswap /dev/zram1", TAG+="systemd"

Add /dev/zram to your fstab.

/etc/fstab
/dev/zram0 none swap defaults 0 0
/dev/zram1 none swap defaults 0 0

Using the graphic card’s RAM

In the unlikely case that you have very little RAM and a surplus of video RAM, you can use the latter as swap. See Swap on video RAM.

Improving system responsiveness under low-memory conditions

On traditional GNU/Linux system, especially for graphical workstations, when allocated memory is overcommitted, the overall system’s responsiveness may degrade to a nearly unusable state before either triggering the in-kernel OOM-killer or a sufficient amount of memory got free (which is unlikely to happen quickly when the system is unresponsive, as you can hardly close any memory-hungry applications which may continue to allocate more memory). The behaviour also depends on specific setups and conditions, returning to a normal responsive state may take from a few seconds to more than half an hour, which could be a pain to wait in serious scenario like during a conference presentation.

  • Use a userspace OOM daemon to tackle these automatically (or interactively).

Warning: Triggering OOM killer to kill running applications may lose your unsaved works. It is up to you that either you are patient enough to wait in hope that applications will finally free the memory normally, or you want to bring back unresponsive system as soon as possible.

Sometimes a user may prefer OOM daemon to SysRq because with kernel OOM-killer you cannot prioritize the process to (or not) terminate. To list some OOM daemons:

earlyoom — Simple userspace OOM-killer implementation written in C. Fedora is going to have this in their default Workstation installation .

oomd — OOM-killer implementation based on PSI, requires Linux kernel version 4.20+. Configuration is in JSON and is quite complex. Confirmed to work in Facebook’s production environment.

nohang — Sophisticated OOM handler written in Python, with optional PSI support, more configurable than earlyoom.

low-memory-monitor — GNOME developer’s effort that aims to provides better communication to userspace applications to indicate the low memory state, besides that it could be configured to trigger the kernel OOM-killer. Based on PSI, requires Linux 5.2+.

Description

zram-config — Upstart job to enable zram support

Property Value
Operating system Linux
Distribution Ubuntu 16.04 LTS (Xenial Xerus)
Repository Ubuntu Universe i386
Official
Package filename zram-config_0.5_all.deb
Package name zram-config
Package version 0.5
Package release
Package architecture all
Package type deb
Homepage
License
Maintainer Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Download size 4.21 KB
Installed size 54.00 KB
Category universe/utils
This installs a simple Upstart job to enable zram support
on kernels that have the module available.

8) Stats¶

Per-device statistics are exported as various nodes under /sys/block/zram<id>/

A brief description of exported device attributes follows. For more details
please read Documentation/ABI/testing/sysfs-block-zram.

Name access description
disksize RW show and set the device’s disk size
initstate RO shows the initialization state of the device
reset WO trigger device reset
mem_used_max WO reset the mem_used_max counter (see later)
mem_limit WO specifies the maximum amount of memory ZRAM can
use to store the compressed data
writeback_limit WO specifies the maximum amount of write IO zram
can write out to backing device as 4KB unit
writeback_limit_enable RW show and set writeback_limit feature
max_comp_streams RW the number of possible concurrent compress
operations
comp_algorithm RW show and change the compression algorithm
compact WO trigger memory compaction
debug_stat RO this file is used for zram debugging purposes
backing_dev RW set up backend storage for zram to write out
idle WO mark allocated slot as idle

User space is advised to use the following files to read the device statistics.

File /sys/block/zram<id>/stat

Represents block layer statistics. Read Documentation/block/stat.rst for
details.

File /sys/block/zram<id>/io_stat

The stat file represents device’s I/O statistics not accounted by block
layer and, thus, not available in zram<id>/stat file. It consists of a
single line of text and contains the following stats separated by
whitespace:

File /sys/block/zram<id>/mm_stat

The mm_stat file represents the device’s mm statistics. It consists of a single
line of text and contains the following stats separated by whitespace:

File /sys/block/zram<id>/bd_stat

The bd_stat file represents a device’s backing device statistics. It consists of
a single line of text and contains the following stats separated by whitespace:

Graphics

Xorg configuration

Graphics performance may depend on the settings in ; see the NVIDIA, ATI, AMDGPU and Intel articles. Improper settings may stop Xorg from working, so caution is advised.

Mesa configuration

adriconf (Advanced DRI Configurator) — GUI tool to configure Mesa drivers by setting options and writing them to the standard drirc file.

DRIconf — Configuration applet for the Direct Rendering Infrastructure. It allows customizing performance and visual quality settings of OpenGL drivers on a per-driver, per-screen and/or per-application level.

Overclocking

As with CPUs, overclocking can directly improve performance, but is generally recommended against. There are several packages in the AUR, such as AUR (old AMD/ATI cards), AUR (recent AMD cards), AUR (old NVIDIA — up to Geforce 9), and for recent NVIDIA cards.

See or .

WARNING¶

For the sake of simplicity we skip error checking parts in most of the
examples below. However, it is your sole responsibility to handle errors.

zram sysfs attributes always return negative values in case of errors.
The list of possible return codes:

-EBUSY an attempt to modify an attribute that cannot be changed once
the device has been initialised. Please reset device first.
-ENOMEM zram was not able to allocate enough memory to fulfil your
needs.
-EINVAL invalid input has been provided.

If you use ‘echo’, the returned value is set by the ‘echo’ utility,
and, in general case, something like:

echo 3 > /sys/block/zram0/max_comp_streams
if ; then
        handle_error
fi

Introduction

The zram driver creates a compressed block device in ram. That block device can then be used for swap or general purpose ram disk. The two most popular uses for it are swap to extend the available amount of ram to processes and /tmp. The ram used for the block device is dynamically obtained and released up to it’s predefined uncompressed maximum size. The way it extends the amount of available ram to a system is by using a portion of the ram as compressed swap. It can therefore hold more pages of memory in the compressed swap than the amount of actual memory used. Typically it compresses to a 3:1 ratio. So, 1G of swap uses only 333MB of ram on average. The compression ratio including memory used for disk overhead varies depending on the % maximum space used. I found it to vary from 1.5:1 for a 1.5G disk with only 5% space used, to over 3:1 when nearly full. It also is much faster at swapping pages than typical hard disk swap.

My experience with using it, my system is still fully functional, with only slight slow downs at times. This is for a Xfce4 desktop with several apps and emerge running with . The memory and swap spaces were nearly maxed out. Intel Core2 Quad core 2.6Ghz, 4G ram. I had 4 — 1.5G zram disks for swap, plus 1G partition of hard drive swap as backup. At one point during linking chromium, I saw the system using just over 5G of zram swap, while using about 1.2G of ram, about 100MB of hard disk swap. The desktop was still responsive 🙂

Download Page for zram-config_0.5_all.deb

If you are running Ubuntu, it is strongly suggested to use a package manager like aptitude or synaptic to download and install packages, instead of doing so manually via this website.

You should be able to use any of the listed mirrors by adding a line to your /etc/apt/sources.list like this:

deb http://cz.archive.ubuntu.com/ubuntu xenial main universe

Replacing cz.archive.ubuntu.com/ubuntu with the mirror in question.

You can download the requested file from the pool/universe/z/zram-config/ subdirectory at any of these sites:

North America

  • mirrors.kernel.org/ubuntu
  • ftp.osuosl.org/pub/ubuntu
  • lug.mtu.edu/ubuntu
  • ubuntu.mirrors.tds.net/ubuntu
  • ubuntu.secs.oakland.edu
  • mirror.mcs.anl.gov/pub/ubuntu
  • mirrors.cat.pdx.edu/ubuntu
  • ubuntu.cs.utah.edu/ubuntu
  • ftp.ussg.iu.edu/linux/ubuntu
  • mirrors.xmission.com/ubuntu
  • mirrors.cs.wmich.edu/ubuntu
  • gulus.USherbrooke.ca/pub/distro/ubuntu

Asia

  • kr.archive.ubuntu.com/ubuntu
  • th.archive.ubuntu.com/ubuntu
  • mirror.lupaworld.com/ubuntu
  • kambing.vlsm.org/ubuntu
  • ubuntu.mithril-linux.org/archives
  • mirror.in.th/ubuntu
  • mirror.rootguide.org/ubuntu

Africa

za.archive.ubuntu.com/ubuntu

Europe

  • cz.archive.ubuntu.com/ubuntu
  • de.archive.ubuntu.com/ubuntu
  • dk.archive.ubuntu.com/ubuntu
  • es.archive.ubuntu.com/ubuntu
  • fr.archive.ubuntu.com/ubuntu
  • ge.archive.ubuntu.com/ubuntu
  • gr.archive.ubuntu.com/ubuntu
  • hr.archive.ubuntu.com/ubuntu
  • mt.archive.ubuntu.com/ubuntu
  • nl.archive.ubuntu.com/ubuntu
  • no.archive.ubuntu.com/ubuntu
  • se.archive.ubuntu.com/ubuntu
  • yu.archive.ubuntu.com/ubuntu
  • nz.archive.ubuntu.com/ubuntu
  • nz2.archive.ubuntu.com/ubuntu
  • ftp.iinet.net.au/pub/ubuntu
  • mirror.optus.net/ubuntu
  • ftp.filearena.net/pub/ubuntu
  • mirror.pacific.net.au/linux/ubuntu

If none of the above sites are fast enough for you, please see our complete mirror list.

Note that in some browsers you will need to tell your browser you want the file saved to a file. For example, in Firefox or Mozilla, you should hold the Shift key when you click on the URL.

More information on zram-config_0.5_all.deb:

Exact Size 4312 Byte (4.2 kByte)
MD5 checksum 59e06d82fad8b1f3701296d1cab765dc
SHA1 checksum bd4215a39b070aca4a164b23ffb9c00f3845d92e
SHA256 checksum 0510dcb3fddcf4cd383b2356ef8322fda89fab85b4954988708dc10418229efb

See Also

Package Description
zsh-antigen_2.2.3-1_all.deb manage your zsh plugins
zsh-static_5.4.2-3ubuntu3_amd64.deb shell with lots of features (static link)
zsh-syntax-highlighting_0.6.0-1_all.deb Fish shell like syntax highlighting for zsh
zsh-theme-powerlevel9k_0.6.4-1_all.deb powerlevel9k is a theme for zsh which uses powerline fonts
zshdb_0.92-3_all.deb debugger for Z-Shell scripts
zssh_1.5c.debian.1-4_amd64.deb interactive file transfers over ssh
zstd_1.3.3+dfsg-2ubuntu1_amd64.deb fast lossless compression algorithm — CLI tool
zsync_0.6.2-3ubuntu1_amd64.deb client-side implementation of the rsync algorithm
ztclocalagent_5.0.0.30-0ubuntu2_amd64.deb sample application demonstrating Zero Touch Configuration
ztex-bmp_20120314-2_amd64.deb universal macro processor
zulucrypt-cli_5.4.0-2build1_amd64.deb tool for encrypting volumes
zulucrypt-gui_5.4.0-2build1_amd64.deb graphical front end for zulucrypt-cli
zulumount-cli_5.4.0-2build1_amd64.deb tool that manages encrypted volumes
zulumount-gui_5.4.0-2build1_amd64.deb graphical front end for zulumount-cli
zulupolkit_5.4.0-2build1_amd64.deb handler the polkit privileges

See Also

Package Description
zsh-antigen_1-3_all.deb manage your zsh plugins
zsh-lovers_0.8.3-0ubuntu2_all.deb tips, tricks and examples for the zsh
zsh-static_5.1.1-1ubuntu2_i386.deb shell with lots of features (static link)
zsh-syntax-highlighting_0.4.1-1_all.deb Fish shell like syntax highlighting for zsh
zshdb_0.09+git20150123-1_all.deb debugger for Z-Shell scripts
zsnes_1.510+bz2-8build1_i386.deb Emulator of the Super Nintendo Entertainment System
zssh_1.5c.debian.1-3.2_i386.deb interactive file transfers over ssh
zstd_0.5.1-1_i386.deb fast lossless compression algorithm — CLI tool
zsync_0.6.2-1ubuntu1_i386.deb client-side implementation of the rsync algorithm
ztclocalagent_5.0.0.30-0ubuntu1_i386.deb sample application demonstrating Zero Touch Configuration
ztex-bmp_20120314-2_i386.deb universal macro processor
zulucrypt-cli_4.7.7-3_i386.deb tool for encrypting volumes
zulucrypt-gui_4.7.7-3_i386.deb graphical front end for zulucrypt-cli
zulumount-cli_4.7.7-3_i386.deb tool that manages encrypted volumes
zulumount-gui_4.7.7-3_i386.deb graphical front end for zulumount-cli
Добавить комментарий

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

Adblock
detector