我想在Linux机器上创建一个接近100%的负载。这是四核系统,我要所有核都全速运转。理想情况下,CPU负载将持续一段指定的时间,然后停止。我希望bash里有什么妙招。我在想某种无限循环。
当前回答
虽然我迟到了,但这篇文章是谷歌搜索“在linux中生成负载”的顶级结果之一。
标记为solution的结果可以用来生成系统负载,我更倾向于使用sha1sum /dev/zero来对cpu内核施加负载。
其思想是从一个无限的数据流(例如。/dev/zero, /dev/urandom,…)该进程将尝试最大化一个cpu-core,直到进程终止。 要为更多内核生成负载,可以将多个命令连接在一起。
如。产生2个核心负荷: Sha1sum /dev/zero | Sha1sum /dev/zero
其他回答
使用这里提到的例子,以及IRC的帮助,我开发了自己的CPU压力测试脚本。它使用每个线程一个子shell和无限循环技术。您还可以交互地指定线程数和时间量。
#!/bin/bash
# Simple CPU stress test script
# Read the user's input
echo -n "Number of CPU threads to test: "
read cpu_threads
echo -n "Duration of the test (in seconds): "
read cpu_time
# Run an endless loop on each thread to generate 100% CPU
echo -e "\E[32mStressing ${cpu_threads} threads for ${cpu_time} seconds...\E[37m"
for i in $(seq ${cpu_threads}); do
let thread=${i}-1
(taskset -cp ${thread} $BASHPID; while true; do true; done) &
done
# Once the time runs out, kill all of the loops
sleep ${cpu_time}
echo -e "\E[32mStressing complete.\E[37m"
kill 0
利用这里的想法,创建的代码在设定的持续时间后自动退出,不需要杀死进程
#!/bin/bash
echo "Usage : ./killproc_ds.sh 6 60 (6 threads for 60 secs)"
# Define variables
NUM_PROCS=${1:-6} #How much scaling you want to do
duration=${2:-20} # seconds
function infinite_loop {
endtime=$(($(date +%s) + $duration))
while (($(date +%s) < $endtime)); do
#echo $(date +%s)
echo $((13**99)) 1>/dev/null 2>&1
$(dd if=/dev/urandom count=10000 status=none| bzip2 -9 >> /dev/null) 2>&1 >&/dev/null
done
echo "Done Stressing the system - for thread $1"
}
echo Running for duration $duration secs, spawning $NUM_PROCS threads in background
for i in `seq ${NUM_PROCS}` ;
do
# Put an infinite loop
infinite_loop $i &
done
加载3个核5秒:
seq 3 | xargs -P0 -n1 timeout 5 yes > /dev/null
这将导致许多write()系统调用带来的高内核(sys)负载。
如果你更喜欢用户区cpu负载:
seq 3 | xargs -P0 -n1 timeout 5 md5sum /dev/zero
如果你只是想继续加载,直到按下Ctrl-C:
seq 3 | xargs -P0 -n1 md5sum /dev/zero
无限循环也是我的想法。一个看起来很怪异的例子是:
while :; do :; done
(:与true相同,不执行任何操作并以0退出)
你可以在子shell中调用它并在后台运行。执行$num_cores次数应该就足够了。在睡眠到所需的时间后,您可以将它们全部杀死,使用jobs -p获得pid(提示:xargs)
你也可以
dd if=/dev/zero of=/dev/null
要运行更多这样的程序,将负载放在更多的内核上,请尝试fork:
fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd
重复花括号中的命令的次数与您想要生成的线程数相同(这里是4个线程)。 简单的输入hit将停止它(只要确保没有其他dd在这个用户上运行,否则也会杀死它)。