系统环境:Ubuntu:24.04
zRam可以将内存压缩存储,能在有限的物理内存中存放更多的数据。
和 swap 不同的是,zRam 的数据还是存放在内存中,比在 swap 文件中的数据读写速度更高,缺点是会消耗一定的 CPU。
对于小内存的机器,开启 zRam 和 swap 都是能缓解内存紧张。
安装zram工具
apt install zram-tools
编辑配置文件
root@linux:~# cat /etc/default/zramswap
# Compression algorithm selection
# speed: lz4 > zstd > lzo
# compression: zstd > lzo > lz4
# This is not inclusive of all that is available in latest kernels
# See /sys/block/zram0/comp_algorithm (when zram module is loaded) to see
# what is currently set and available for your kernel[1]
# [1] https://github.com/torvalds/linux/blob/master/Documentation/blockdev/zram.txt#L86
ALGO=zstd
# Specifies the amount of RAM that should be used for zram
# based on a percentage the total amount of available memory
# This takes precedence and overrides SIZE below
PERCENT=50
# Specifies a static amount of RAM that should be used for
# the ZRAM devices, this is in MiB
#SIZE=256
# Specifies the priority for the swap devices, see swapon(2)
# for more details. Higher number = higher priority
# This should probably be higher than hdd/ssd swaps.
PRIORITY=100
参数说明
- ALGO:压缩算法,lz4 速度最快,压缩比最低。zstd 速度居中,压缩比最高。CPU 如果冗余比较多可以选择zstd
- PERCENT:内存占比,占用物理内存的最大百分比。优先级高于 SIZE 配置
- Size:固定大小分配,如果设置了PERCENT,那这个参数失效。
- PRIORITY:优先级,Swap 优先级是-2,建议设置 100,有限写入 zRam
重启服务生效
systemctl restart zramswap
查看 zram 的使用情况
root@linux:~# swapon --show
NAME TYPE SIZE USED PRIO
/swap.img file 1.9G 0B -2
/dev/zram0 partition 983.8M 549.1M 100
root@linux:~# zramctl
NAME ALGORITHM DISKSIZE DATA COMPR TOTAL STREAMS MOUNTPOINT
/dev/zram0 zstd 983.8M 548.8M 122.1M 126.6M 2 [SWAP]
zramctl 的输出可以看到,Data 数据大小 548.8M,ToTal 实际占用 126.6M,作用还是很明显的。
另外,可以调整内核参数,几乎所有非活跃进程进入压缩状态。极致节省物理内存,但 CPU 负载会升高。
root@linux:~# sysctl vm.swappiness
vm.swappiness = 150
vm.swappiness 的值可以设置为 100-200 之间。