CentOS Swap性能测试方法
在进行Swap性能测试前,需先创建或启用Swap空间(若未配置)。常见方式包括创建Swap文件或使用Swap分区:
# 创建2GB空白文件
dd if=/dev/zero of=/swapfile bs=1G count=2
# 设置文件权限(仅root可读写)
chmod 600 /swapfile
# 格式化为Swap格式
mkswap /swapfile
# 激活Swap
swapon /swapfile
# 永久生效(添加至/etc/fstab)
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
mkswap /dev/sdb1
swapon /dev/sdb1
echo '/dev/sdb1 swap swap defaults 0 0' >> /etc/fstab
fio是Linux下强大的I/O测试工具,可模拟Swap的实际使用场景(随机/顺序读写、多线程),输出IOPS、带宽、延迟等关键指标。
yum install -y fio
fio --ioengine=libaio --bs=4k --direct=1 --thread --time-based --rw=randread --filename=/swapfile --runtime=60 --numjobs=1 --iodepth=1 --group_reporting --name=randread_test
fio --ioengine=libaio --bs=4k --direct=1 --thread --time-based --rw=randwrite --filename=/swapfile --runtime=60 --numjobs=1 --iodepth=1 --group_reporting --name=randwrite_test
fio --ioengine=libaio --bs=1M --direct=1 --thread --time-based --rw=read --filename=/swapfile --runtime=60 --numjobs=1 --iodepth=1 --group_reporting --name=read_bw_test
fio --ioengine=libaio --bs=1M --direct=1 --thread --time-based --rw=write --filename=/swapfile --runtime=60 --numjobs=1 --iodepth=1 --group_reporting --name=write_bw_test
--ioengine=libaio:使用异步I/O引擎,提升测试准确性;--bs=4k:块大小(4KB,匹配大多数磁盘的默认块大小);--direct=1:绕过系统缓存,直接测试Swap设备的真实性能;--rw=randread/randwrite/read/write:测试类型(随机读/随机写/顺序读/顺序写);--runtime=60:测试时长(60秒);--numjobs=1:线程数(1个线程);--iodepth=1:队列深度(1个未完成I/O请求)。sysbench是多功能性能测试工具,可测试CPU、内存、磁盘等,间接反映Swap对系统的影响。
yum install -y sysbench
sysbench memory --memory-block-size=1M --memory-total-size=4G --threads=4 run
此命令会分配4GB内存(超过系统物理内存时触发Swap),通过观察系统日志或free -h命令查看Swap使用情况。测试过程中需实时监控Swap状态,确认测试有效性:
free -h
输出示例: total used free shared buff/cache available
Mem: 1.8G 1.2G 100M 100M 500M 300M
Swap: 2.0G 500M 1.5G
swapon --show
输出示例:NAME TYPE SIZE USED PRIO
/swapfile file 2G 500M -2
vmstat 1 5 # 每秒采样1次,共5次
关注si(从Swap到内存的交换速率,KB/s)、so(从内存到Swap的交换速率,KB/s)指标,若持续不为0,说明Swap正在频繁使用。swapoff /swapfile
rm -f /swapfile
sed -i '/\/swapfile/d' /etc/fstab