Increasing Swap Size of Raspberry Pi
Jun 18, 2023
Your Raspberry Pi is crashing because the RAM is not enough? No problem!
Jul 1, 2023 06:16 PM
According to the Read Hat Documentation on Massachusetts Institute of Technology website:
“Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory.”
You can check the available and used RAM amount on Raspberry Pi by running
free -h. Using the
-hflag to make values human readable. Here is the output on my system:
This means that I have a total of 3.7 GB of RAM (56 MB of it is being used) and 99 MB of Swap space.
We need to disable the swap in order to increase it because it cannot be used while being edited.
sudo dphys-swapfile swapoff
After the execution of the line above, the available swap space is now 0 B.
The swap file is the file that keeps the swap size configuration on Linux systems.
sudo nano /etc/dphys-swapfile
In the file, the line
CONF_SWAPSIZEis the swap size amount in megabytes. You can increase it to the required amount. I used 1024 MB.
Exit nano by saving your changes with ctrl+X and Y (control+X and Y for Mac)
To enable the swap space again, we need to run the command below. After the execution, you can see the system creates a new swap file to use.
sudo dphys-swapfile swapon
After this command, to make the system able to use the new swap file; you need to reboot your Raspberry Pi with the
You can check the swap size by executing
free -hjust like at the beginning of the post. Here is my output, it is 1 GB now:
The swap space is useful if you are doing a one-time job that doesn’t require speed as a priority but successful execution just like compiling a project. If you need more memory while executing your program on a normal basis, you have two options; optimize your program or get a system with more memory. The fastest versions of the off-the-shelf Micro SD cards are going to be creating a real bottleneck for the real-time execution and it would harm the Micro SD card to be used as a memory space (reading and writing too frequently). So my suggestion would be to increase the swap space temporarily and decrease it after your job is done.