消耗服务器cpu和内存

编程入门 行业动态 更新时间:2024-10-27 16:33:32

<a href=https://www.elefans.com/category/jswz/34/1766630.html style=消耗服务器cpu和内存"/>

消耗服务器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 releaseFILE_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
doi=i+100;i=100
done" | /bin/bash &
}function consume()
{
for i in `seq $1`
doendless_looppid_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)
dokill -9 $pid
done
}function main()
{
case "$1" inconsume) 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 releaseFILE_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 ];thenecho "/tmp/memory already exists"
elsemkdir /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 ]; thenecho "remove memory data failed"return $ret
fiumount /tmp/memory;ret=$?
if [ $ret != 0 ]; thenecho "umount memory filedir failed"return $ret
firmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; thenecho "remove memory filedir failed"return $ret
fi}function main()
{
case "$1" inconsume) 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() {@Overridepublic 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() {@Overridepublic 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]; // 100Mv.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]; // 100Mv.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和内存的脚本完成

更多推荐

消耗服务器cpu和内存

本文发布于:2024-03-06 18:42:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1716085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:消耗   内存   服务器   cpu

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!