zswap: improve memory performance on Linux
Zwap is a Linux kernel module that will attempt to compress memory pages and keep them in ram before swapping to disk. This is helpful on low memory systems and will result in a noticeable performance improvement in most cases. It is required that a swap device exists. Here are some commands to enable it on Linux. Tested on Debian and Ubuntu.
sudo perl -pi -e 's/^(GRUB_CMDLINE_LINUX_DEFAULT.*)"$/$1 zswap.enabled=1 zswap.compressor=lz4 zswap.zpool=z3fold zswap.max_pool_percent=25"/' /etc/default/grub
sudo update-grub
sudo echo -e 'lz4\nlz4_compress\nz3fold' >> /etc/initramfs-tools/modules
sudo update-initramfs -u
sudo reboot
This will update grub to instruct linux to load the required modules, set sensible parameters, and add the modules to initramfs so they are able to be loaded early in the boot process.
Explanation of parameters:
zswap.enabled=1 #enable zswap
zswap.compressor=lz4 #use lz4 compression, the best balance of speed and performance
zswap.zpool=z3fold #the z3fold allocator stores up to three compressed pages per physical page, allowing for a higher compression ratio
zswap.max_pool_percent=25 #max percent of ram that may be used for compressed pages. Default is 20, I like to bump it up just a little. Be careful not to go too high or there won't be any memory left for cache and it will hurt performance instead of helping it.
This is especially helpful on low end systems with <= 4GB RAM. It also works well those t2.nano instances and other low memory VPS instances.
Here are some commands to check if it is working:
cat /sys/module/zswap/parameters/enabled
should return Y
examine all debug parameters for the modulesudo grep -R . /sys/kernel/debug/zswap/
view current compression ratiosudo bash -c 'echo "scale=2; " $(</sys/kernel/debug/zswap/stored_pages) " * 4096 /" $(</sys/kernel/debug/zswap/pool_total_size) | bc'