作用:控制消耗cpu的百分比,配合某些测试项目使用
实现:设计包含死循环的函数,放入后台运行,通过控制个数实现控制消耗CPU资源的百分比
演示:
直接输入进程个数, 通过top指令查看cpu消耗百分比,不输入数字直接回车则表示清除所有后台函数
代码专区:
#/bin/bash # LY # ------------------ # Copyright 2016.04.17 LingYi ([email protected]) QQ:1519952564 cpu_(){ while :; do echo "This is a test information" >/dev/null sleep 0.1 done } kill_cpu_(){ i=1 for process in $(ps aux | grep $1 | head -n -1 | awk ‘{print $2}‘); do if [[ ${process} != ${2} ]]; then kill -9 ${process}; let i++; fi let i++ done } echo -e "\033[1;32mInput one number of the processes that will run in background.\033[0m" echo -e "\033[1;32mWhen they are running, you can use the command \"top\" to monitor in another window.\033[0m" echo -e "\033[1;32mKill the all processes, just press \"Enter\" key with inputing nothing.\033[0m" echo -e "\033[1;32m\"Ctrl + c\" or press "Q" to exit.\033[0m" while :; do echo -ne "\033[1;34m\nInput number [ 1 - N ]: " echo -ne "\033[1;31m" read num_moment echo -ne "\033[0m" if [[ ${num_moment} == ‘q‘ ]] || [[ ${num_moment} == ‘Q‘ ]]; then exit 0; fi if [[ ! -z ${num} ]]; then kill_cpu_ $0 $$ >/dev/null 2>&1; fi num=${num_moment} for ((i=1; i<=num; i++)); do cpu_ & done done
时间: 2024-10-14 03:46:25