Linux内存测试---构造消耗内存shell脚本

原文:https://blog.csdn.net/mpu_nice/article/details/106918188

 

实现思想:借鉴虚拟内存的思想,创建虚拟内存文件系统,不断写入数据达到消耗内存的目的,需要清除内存时,删除创建的虚拟内存目录即可。

#使用虚拟内存构造内存消耗

mkdir /tmp/memory

mount -t tmpfs -o size=1024M tmpfs /tmp/memory

dd if=/dev/zero of=/tmp/memory/block

#释放消耗的虚拟内存

rm /tmp/memory/block

umount /tmp/memory

rmdir /tmp/memory

 

下面的代码为自己平时在测试过程中需要构造linux内存使用率的场景内存测试:

#!/bin/bash
# Destription: testing memory usage
# Example : sh memory_usage.sh 500M | sh memory_usage.sh 1G | sh memory_usage.sh release

FILE_NAME=`basename $0`
memsize=$2
function usage()
{
echo "Usage:$FILE_NAME consume memory_size|release -----the value of memory_size like 100M 2G and etc"
echo "Example: $FILE_NAME consume 1G"
echo " $FILE_NAME release"
}
function consume()
{
if [ -d /tmp/memory ];then
echo "/tmp/memory already exists"
else
mkdir /tmp/memory
fi
mount -t tmpfs -o size=$1 tmpfs /tmp/memory
dd if=/dev/zero of=/tmp/memory/block

}

function release()
{
rm /tmp/memory/block;ret=$?
if [ $ret != 0 ]; then
echo "remove memory data failed"
return $ret
fi

umount /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "umount memory filedir failed"
return $ret
fi

rmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "remove memory filedir failed"
return $ret
fi

}

function main()
{
case "$1" in
consume) consume $memsize;;
release) release;;
*) usage;exit 1;;
esac
}

main $*
测试结果:


————————————————
版权声明:本文为CSDN博主「mBeNice」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mpu_nice/article/details/106918188

posted @ 2021-11-08 11:04  wangmo  阅读(1564)  评论(0编辑  收藏  举报