Skip to content

Instantly share code, notes, and snippets.

Last active Apr 28, 2021
What would you like to do?
Tool for extracting compression ratio and amount of compressed memory from zram swap partitions.


This is a simple tool for displaying memory information including compression ratio and percentage of compressed memory in Linux kernel using zram. This tool works without zram, but in that case it displays only basic memory statistics.

With LC_NUMERIC=en_GB.utf8 the output of ./zraminfo looks like this:

Physical memory:       4,111,052,800 bytes
Buffers and cache:       599,769,088 bytes / 14.6% of physical memory
Unallocated:             166,268,928 bytes /  4.0% of physical memory
Compressed:              348,880,896 bytes /  8.5% of physical memory
Decompressed size:       967,163,904 bytes / 20.5% of decompressed memory
Compression ratio: 2.772

If zram is not familiar to you, see article in Wikipedia. If you are using recent Debian or Ubuntu, you can start using zram by installing zram-config:

sudo apt-get install zram-config
#!/bin/sh -eu
# Iterate through swap devices searching for compressed ones
while read NAME _; do
# Filter zram swaps and let's hope your ordinary swap doesn't have
# "zram" in its name :D
case $NAME in
*zram*) ;;
*) continue
DIR=/sys`udevadm info --query=path --name=$NAME`
DATA=$(awk '{print $1}' $DIR/mm_stat)
COMP=$(awk '{print $3}' $DIR/mm_stat)
done </proc/swaps
# Extract physical memory in kibibytes and scale back to bytes
read _ MEM_KIB _
read _ FREE_KIB _
read _ BUF_KIB _
read _ CACHE_KIB _
} </proc/meminfo
/usr/bin/printf "\
Physical memory: %'17d bytes
Buffers and cache: %'17d bytes / %4.1f%% of physical memory
Unallocated: %'17d bytes / %4.1f%% of physical memory
" `echo "scale=6; 1024*$MEM_KIB; 1024*($BUF_KIB+$CACHE_KIB); 100*($BUF_KIB+$CACHE_KIB)/$MEM_KIB; 1024*$FREE_KIB; 100*$FREE_KIB/$MEM_KIB"|bc`
if test "$HAS_ZRAM"; then
/usr/bin/printf "\
Compressed: %'17d bytes / %4.1f%% of physical memory
Decompressed size: %'17d bytes / %4.1f%% of decompressed memory
Compression ratio: %.3f
echo "Compressed: 0 bytes / zram not in use"

This comment has been minimized.

Copy link

@CarlosGS CarlosGS commented Dec 3, 2020

Awesome script, thanks!!

(Was giving error "orig_data_size: No such file", works with the fix in )


This comment has been minimized.

Copy link
Owner Author

@zouppen zouppen commented Dec 4, 2020

(Was giving error "orig_data_size: No such file", works with the fix in )

Thanks a lot! The sysfs structure has changed in 6 years :-) Your patch has been merged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment