消耗服务器cpu和内存

背景:接到一个需求服务器的cpu利用率必须达到16%以上,不然会回收部分服务器资源。写一个程序消耗服务器cpu资源但要保持在16%不能太高也不能太低。

  1. shell脚本消耗cpu和内存。要么消耗1颗要么消耗2颗整数递增。感觉有点假。
  2. java程序消耗cpu和内存。可以按照百分比消耗。可以以假乱真。

shell消耗cpu脚本cpu.sh

#!/bin/bash
# Destription: test cpu usage 
# Example    : sh cpu_usage.sh consume 8 | sh cpu_usage.sh release
 
FILE_NAME=`basename $0`
cpunum=$2
pid_array=()
function usage()
{
echo "Usage:$FILE_NAME consume cpu_number|release -----the value of cpu_number is an integer,such as 1,2,3"
echo "Example: $FILE_NAME consume 12"
echo "         $FILE_NAME release"
}
 
function endless_loop()
{
echo -ne "i=0;
while true
do
    i=i+100;
    i=100
done" | /bin/bash &
}
 
 
function consume()
{
for i in `seq $1`
do
    endless_loop
    pid_array[$i]=$!
done
echo "consume cpu resources process ids are: ${pid_array[*]}"
}
 
function release()
{
for pid in $(ps -ef |grep /bin/bash |grep -v grep |awk '{print $2}' |xargs)
do
    kill -9 $pid
done
}
 
function main()
{
case "$1" in
    consume) consume $cpunum;;
    release) release;;
          *) usage;exit 1;;
esac
}
 
main $*

使用之前使用命令先查询下cpu的个数cat /proc/cpuinfo | grep “processor”|wc -lgrep processor /proc/cpuinfo |wc -l
需要构造消耗2颗cpu的资源运行脚本sh cpu.sh consume 2,此时运行top命令查看cpu的使用率。如果要释放cpu资源,运行sh cpu.sh release即可释放cpu资源。

shell消耗内存脚本memory.sh

#!/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 $*

sh memory.sh consume 1G 即消耗1G的内存,sh memory.sh release取消消耗内存。

至此shell脚本消耗内存和cpu的代码完成

java消耗cpu和内存的脚本

package com.example.demo.cpu;

import java.util.Vector;

/**
 * CPU 内存 控制
 *
 * @author smy
 */
public class JavaListener {


    public static final double TIME = 1000;

    public static final double MB100 = 104857600;


    public static void main(String[] args) {
        if (args == null || args.length < 1) {
            exit();
        }
        String rates = null, memory = null;
        for (String param : args) {
            if (param.startsWith("-c:")) {

                param = param.substring(3, param.length());
                if (param != null && param.length() > 0) {
                    rates = param;
                }
            }
            if (param.startsWith("-m:")) {

                param = param.substring(3, param.length());
                if (param != null && param.length() > 0) {
                    memory = param;
                }
            }
        }

        if ((rates == null || rates.length() < 1) && (memory == null || memory.length() < 1)) {
            exit();
        }

        if (rates != null && rates.length() > 0) {
            final String[] rateArr = rates.split(",");
            for (String rate : rateArr) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        double r = Double.valueOf(rate) / 100;
                        lineGraph(r);
                    }
                }).start();
            }
        }

        if (memory != null && memory.length() > 0) {

            Integer finalMemory = Integer.valueOf(memory);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    memory(finalMemory);
                }
            }).start();
        }
    }

    private static void exit() {
        System.out.println("Please enter parameters");
        System.out.println("such as: java xxxxx -c:80,40 -m:600");
        System.out.println("-C represents the control core, and - m represents the control memory");
        System.out.println("-c: 80 and 40 represent two cores, with utilization rates of 80% and 40% respectively");
        System.out.println("-m: 600 means about 600MB of memory (unit: megabyte)");
        System.exit(0);
    }

    private static double random() {
        return (7 + Math.random() * (3)) / 10;
    }

    @SuppressWarnings("unchecked")
    private static void memory(int mb) {
        @SuppressWarnings("rawtypes")
        Vector v = new Vector();
        for (int i = 0; i < ((int) mb / 100); i++) {
            int size = (int) (MB100 * random());
            byte b1[] = new byte[size]; // 100M
            v.add(b1);
        }

        while (true) {
            try {
                Thread.sleep(1000);
                System.gc();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (v.size() > 0) {
                v.remove(0);
                int size = (int) (MB100 * random());
                byte b1[] = new byte[size]; // 100M
                v.add(b1);
            }
        }
    }


    private static void lineGraph(double rate) {
        while (true) {

            doSomeSimpleWork(rate * TIME);

            try {
                long sleep = (long) (TIME - rate * TIME);
                if (sleep < 1) {
                    sleep = 1L;
                }
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    private static void doSomeSimpleWork(double time) {
        long startTime = System.currentTimeMillis();
        while ((System.currentTimeMillis() - startTime) < time) {
            // do nothing
        }
    }
}

编译注意包名,javac JavaListener.java -d . 生成class文件。启动(只占用其中两核心,分别占用60%、60%;占用50兆内存左右)java com.example.demo.cpu.JavaListener-c:60,60 -m:50 & 这里注意com.example.demo.cpu是class文件的包名,也就是java文件的package目录必须要加,否则报错找不到主类。

添加到服务器crontab中定时执行

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
#30分钟一次执行脚本
*/30 * * * * root sh /repo/hict-cpu/start.sh

启动脚本在/repo/hict-cpu/下创建vi start.sh

#!/bin/bash
source /etc/profile
SERVICE_NAME=com.example.demo.cpu.JavaListener
echo ">>> kill -9 $(jps -ml | grep $SERVICE_NAME | awk '{print $1}')"
kill -9 $(jps -ml | grep $SERVICE_NAME | awk '{print $1}')
#一定要加否则找不到这个目录
cd /repo/hict-cpu/
java $SERVICE_NAME -c:60,60 -m:50 &

至此java消耗服务器cpu和内存的脚本完成

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值