Linux中Swap(即:交换分区),类似于Windows的虚拟内存,就是当内存不足的时候,把一部分硬盘空间虚拟成内存使用,从而解决内存容量不足的情况。
在安装Linux系统的时候需要单独设置swap分区而Windows安装没有此要求,主要原因是实现的方式不同:
- Windows的虚拟内存在C盘上动态分配(即使内存不用玩也会使用)
- Linux的虚拟内存需要单独建立swap分区(内存用完时才会使用或进入休眠时使用)
从流程上说Windows的更加方便并且大小是动态的,但是同样会存在问题,比如虚拟内存交换文件混在系统分区里面使用,文件碎片问题和容量变动问题都会影响交换文件的效率。而Linux因为是独立的分区,所以没有文件碎片和容量变动的问题。
从原理上,安装Linux不分配swap分区也是可以的,特别是电脑内存足够的情况下。但是为防止意外情况发生,或让电脑支持hibernation(休眠),建议还是分配swap分区。
休眠(Hibernate),将系统切换到该模式后,系统会自动将内存中的数据全部转存到硬盘上一个休眠文件中,然后切断对所有设备的供电。这样当恢复的时候,系统会从硬盘上将休眠文件的内容直接读入内存,并恢复到休眠之前的状态。这种模式完全不耗电,因此不怕休眠后供电异常,但代价是需要一块和物理内存一样大小的硬盘空间。但由于这种方法完全不耗电又能保存工作状态,往往被笔记本用户用来作为关机的替代方式。
Linux下Swap分区的大小如何确定?一起来看下专家的建议。
来自RedHat官方的建议:
Table 8.3. Recommended System Swap Space
Amount of RAM in the system | Recommended swap space | Recommended swap space if allowing for hibernation |
less than 2GB | 2 times the amount of RAM | 3 times the amount of RAM |
2GB – 8GB | Equal to the amount of RAM | 2 times the amount of RAM |
8GB – 64GB | 4GB to 0.5 times the amount of RAM | 1.5 times the amount of RAM |
more than 64GB | workload dependent (at least 4GB) | hibernation not recommended |
At the border between each range listed above (for example, a system with 2 GB, 8 GB, or 64 GB of system RAM), discretion can be exercised with regard to chosen swap space and hibernation support. If your system resources allow for it, increasing the swap space can lead to better performance.
来自Ubuntu官方的建议:
RAM No hibernation With Hibernation Maximum 256MB 256MB 512MB 512MB 512MB 512MB 1024MB 1024MB 1024MB 1024MB 2048MB 2048MB RAM No hibernation With Hibernation Maximum 1GB 1GB 2GB 2GB 2GB 1GB 3GB 4GB 3GB 2GB 5GB 6GB 4GB 2GB 6GB 8GB 5GB 2GB 7GB 10GB 6GB 2GB 8GB 12GB 8GB 3GB 11GB 16GB 12GB 3GB 15GB 24GB 16GB 4GB 20GB 32GB 24GB 5GB 29GB 48GB 32GB 6GB 38GB 64GB 64GB 8GB 72GB 128GB 128GB 11GB 139GB 256GB 256GB 16GB 272GB 512GB 512GB 23GB 535GB 1TB 1TB 32GB 1056GB 2TB 2TB 46GB 2094GB 4TB 4TB 64GB 4160GB 8TB 8TB 91GB 8283GB 16TB
可以看到Ubuntu给出的建议非常的详细,建议按照此进行设置~