• 消耗服务器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 $*
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    使用之前使用命令先查询下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 $*
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    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
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134

    编译注意包名,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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    启动脚本在/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 &
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

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

  • 相关阅读:
    使用 @antfu/eslint-config 配置 eslint (包含兼容uniapp方法)
    Druid1.2.12版本发布,新增连接池默认配置connectTimeout和socketTimeout详解
    云IDE产品评测感受
    C++进阶-STL的简单认识
    gitlab-ce-12.3.5 挖矿病毒及解决方案
    前端视角看 Docker : 加速开发和部署的利器
    FlyWeight(享元模式)
    基于Nodejs的拼车平台的设计和实现
    Python读取TCP的4字节浮点数
    PFSK164 3BSE021180R1 有源滤波器和无源滤波器的主要区别
  • 原文地址:https://blog.csdn.net/Smy_0114/article/details/127768291