Increasing Swap Size of Raspberry Pi

date
Jun 18, 2023
thumbnail
slug
increase-swap-size-of-raspberry-pi
author
Can Durmus
status
Published
tags
Raspberry Pi
Optimization
Linux
summary
Your Raspberry Pi is crashing because the RAM is not enough? No problem!
type
Post
updatedAt
Jul 1, 2023 06:16 PM

1. First things first, what is SWAP?

“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 -h flag to make values human readable. Here is the output on my system:
notion image
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.

2. Let’s get started, disable the swap

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.
notion image

3. Edit the swap file

The swap file is the file that keeps the swap size configuration on Linux systems.
sudo nano /etc/dphys-swapfile
notion image
In the file, the line CONF_SWAPSIZE is the swap size amount in megabytes. You can increase it to the required amount. I used 1024 MB.
notion image
Exit nano by saving your changes with ctrl+X and Y (control+X and Y for Mac)

4. Enable swap

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
notion image
 
After this command, to make the system able to use the new swap file; you need to reboot your Raspberry Pi with the sudo reboot command.

5. Check

You can check the swap size by executing free -h just like at the beginning of the post. Here is my output, it is 1 GB now:
notion image

6. Conclusion

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.
Â