晓夏

YoungCheung

Zhang Sir's technical way

linux内存测试(占用)脚本

浏览量:653


#!/bin/bash
################################################################
#       mem used script
#       eg. ./mem.sh 60G & to start testing
#       eg. ./mem.sh stop  to stop testing and clear env
################################################################
num=$1
user=`whoami`
 
start()
{
if [ -d /tmp/memory ];then
        echo "the dir "/tmp/memory" is already exist!, use it." >> mem.log
else
        sudo mkdir /tmp/memory
        mount -t tmpfs -o size=$num tmpfs /tmp/memory
fi
dd if=/dev/zero of=/tmp/memory/block >> mem.log 2>&1
}
 
stop()
{
 
rm -rf /tmp/memory/block
umount /tmp/memory
rmdir /tmp/memory
if [ -d /tmp/memory ];then
        echo "Do not remove the dir \"/tmp/memory\", please check "
else
        echo "clear env is done!"
fi
}
main()
{
if [ $num == 'stop' ];then
        stop
elif [ $user != "root" ];then
        echo "please use the \"root\" excute script!"
        exit 1
else
        start
fi
}
 
if [ $# = 2 -o $# = 1 ];then
        main
else
        echo 'Usage: <./mem.sh 60G &> to start  or <./mem.sh stop>  to clear env'
fi


c脚本

/*usage: cc mem.c -o mem.out 后 使用./mem.out 100 & 消耗对应数字MB单位的内存,释放时杀掉对应进程即可*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
 
#define UNIT (1024*1024)
 
int main(int argc, char *argv[])
{
        long long i = 0;
        int size = 0;
 
        if (argc != 2) {
                printf(" === argc must 2\n");
                return 1;
        }
        size = strtoull(argv[1], NULL, 10);
        if (size == 0) {
                printf(" argv[1]=%s not good\n", argv[1]);
                return 1;
        }
 
        char *buff = (char *) malloc(size * UNIT);
        if (buff)
                printf(" we malloced %d Mb\n", size);
        buff[0] = 1;
 
        for (i = 1; i < (size * UNIT); i++) {
                if (i%1024 == 0)
                        buff[i] = buff[i-1]/8;
                else
                        buff[i] = i/2;
        }
        pause();
}


神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。