by  Marirs

Creating Swap space using fallocate

Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.

We already dealt this in the previous post on creating a swap space and tweaking the swappiness setting. However, in the previous post we performed the operation of creating the swap file using the old traditional method.

[[email protected]]$ sudo dd if=/dev/zero of=/swapfile bs=1G count=4
4+0 records in
4+0 records out
4294967296 bytes (4.3 GB) copied, 18.6227 s, 231 MB/s
                    
[[email protected]]$ ls -lh /swapfile
-rw-r–r– 1 root root 4.0G Feb 28 17:15 /swapfile
            

The command above, you may notice that it took quite a while. In fact, you can see in the output that it took my system ~18 seconds to create the swap file. That is because it has to write 4 Gigabytes of zeros to the disk.

There is a faster method to do this: fallocate

This command creates a file of a preallocated size instantly, without actually having to write dummy contents. We can achieve the same swap file by:

[[email protected]]$ sudo fallocate -l 4G /swapfile
[[email protected]]$ ls -lh /swapfile
-rw-r–r– 1 root root 4.0G Feb 28 17:19 /swapfile
            

As you can now see, our file is created with the correct amount of space set aside and almost instantly. Now you can go ahead to create your swap file. If you need instructions on how to do it, follow my previous post.