Linux-提高CPU、内存使用率shell脚本

冬天的秘密 2025-01-08T12:00:13+08:00
0 0 598

引言

在Linux系统中,我们经常需要监控和优化CPU和内存的使用率,以确保系统的稳定性和性能表现。本博客将介绍如何通过编写Shell脚本来提高CPU和内存的使用率,以便进行测试和优化。

提高CPU使用率的Shell脚本

以下是一个简单的Shell脚本,用于提高CPU使用率:

#!/bin/bash

# 设置运行时间和CPU核心数
duration=60
num_cores=$(nproc)

# 计算任务数,并分发到各个CPU核心上运行
let "num_tasks=num_cores*2"

echo "Running CPU stress test..."
echo "Duration: $duration seconds"
echo "Number of CPU cores: $num_cores"
echo "Number of tasks: $num_tasks"

# 使用for循环启动任务并运行,将进程PID保存到数组中
declare -a pids

for ((i=0; i<num_tasks; i++))
do
    echo "Starting task $i"
    yes > /dev/null &
    pids[$i]=$!
done

# 运行指定时间后,停止所有任务
sleep $duration
echo "Stopping CPU stress test..."

for pid in ${pids[@]}
do
    echo "Stopping task with PID $pid"
    kill -9 $pid
done

echo "CPU stress test complete."

以上脚本使用yes命令来持续产生输出,从而占用CPU资源。我们通过控制任务数和运行时间来实现对CPU使用率的调整。任务数等于CPU核心数的两倍可以确保多线程运行,以达到更高的CPU使用率。

提高内存使用率的Shell脚本

以下是一个Shell脚本示例,用于提高内存使用率:

#!/bin/bash

# 设置运行时间和内存使用率目标百分比
duration=60
target_mem_usage=90

# 计算可用内存大小
total_mem=$(free -m | grep Mem | awk '{print $2}')
target_mem=$(echo "$total_mem*$target_mem_usage/100" | bc)

echo "Running memory stress test..."
echo "Duration: $duration seconds"
echo "Target memory usage: $target_mem MB"

# 启动一个while循环,直到达到目标内存使用率或超过最大时间
start_time=$(date +%s)
current_time=$(date +%s)
runtime=$((current_time - start_time))

while [ $runtime -lt $duration ]
do
    # 分配每个进程所需的内存
    let "mem_per_process=target_mem/(runtime+1)"
    
    # 启动一个新的进程并分配内存
    yes > /dev/null & PID=$!
    echo $PID >> pids.txt
    echo "Starting task with PID: $PID, allocated memory: $mem_per_process MB"
    
    # 判断内存是否达到目标使用率
    current_mem=$(free -m | grep Mem | awk '{print $3}')
    if [ $current_mem -ge $target_mem ]; then
        break
    fi

    current_time=$(date +%s)
    runtime=$((current_time - start_time))
done

# 根据已运行时间停止所有任务
sleep $((duration - runtime))
echo "Stopping memory stress test..."

for pid in `cat pids.txt`
do
    echo "Stopping task with PID $pid"
    kill -9 $pid
done

rm pids.txt

echo "Memory stress test complete."

以上脚本不断启动新的进程并分配内存,直到达到预设的内存使用率目标。我们通过控制任务的运行时间和目标内存使用率百分比来调整内存使用率。

结论

通过编写Shell脚本,我们可以轻松地自定义和控制CPU和内存的使用率。这对于系统管理员和开发人员来说非常有用,以便在测试和优化时模拟不同的负载情况。希望本博客对您有所帮助!

相似文章

    评论 (0)