linux下模拟CPU占用100%小程序

linux下模拟CPU占用100%小程序

来源:https://www.cnblogs.com/landhu/p/5924548.html

在做一个测试时,需要模拟服务器CPU占用满的情况,在查阅相关资料后,发现网上程序不太好用,
原文在这:http://www.2cto.com/os/201304/202068.html
优化后如下:

#! /bin/sh 
# filename killcpu.sh
if [ $# -ne 1 ] ; then
  echo "USAGE: $0 <CPUs>|stop"
  exit 1;
fi

stop()
{
 while read LINE
  do
    kill -9 $LINE
    echo "kill $LINE sucessfull"
  done < pid.txt
 cat /dev/null > pid.txt
}

start()
{
  echo "u want to cpus is: "$1
  for i in `seq $1`
do
  echo -ne " 
i=0; 
while true
do
i=i+1; 
done" | /bin/sh &
  pid_array[$i]=$! ;
done

for i in "${pid_array[@]}"; do
  echo 'pid is: ' $i ';';
  echo $i >> pid.txt
done
}

case $1 in
   stop)
    stop
  ;;
   *)
   start $1
;;
esac

linux下模拟CPU占用100%小程序和对应解决建议

来源:https://blog.csdn.net/lin434406218/article/details/54694900

一、单个核100% 
代码kill_cpu.c

#include <stdlib.h>
int main()
{
        while(1);
        return 0; }

这里写图片描述

运行之前的CPU

这里写图片描述

运行:

#  gcc -o out kill_cpu.c
#  ./out

这里写图片描述

结束:Ctrl + C

这里写图片描述

在运行程序之前先在本地测试自己的程序,避免程序的逻辑错误或者死循环的错误。

数据库服务器执行某一个SQL或者存储过程需要大量的运算(一般为软件设计不合理)

二、让所有的核都是100%

$ for i in `seq 1 $(cat /proc/cpuinfo | grep "physical id" | wc -l)`; do ./out & done

这里写图片描述

所有的核都是100%,cat /proc/cpuinfo | grep “physical id” | wc -l 是获取到CPU的核数,逻辑核数。这样每一个cpu上都会调度到一个死循环的进程。

批量kill进程

这里写图片描述

ps aux

显示其他用户启动的进程(a) 
查看系统中属于自己的进程(x) 
启动这个进程的用户和它启动的时间(u)

把大的作业分给多个CPU一起运行,避免单个CPU运行导致CPU消耗过高而引发的系统奔溃问题

三、让某个核100%

当前的进程在cpu2上

这里写图片描述

通过taskset命令绑定CPU(taskset 指定进程运行在某个特定的CPU上)

taskset -cp CPUID   进程ID

这里写图片描述

把某一个任务直接指定一个CPU专门运行,保证该任务快速运行,不会长期拉低整个系统的运作效率

猜你喜欢

转载自www.cnblogs.com/lsgxeva/p/9221558.html
今日推荐