我想在Linux机器上创建一个接近100%的负载。这是四核系统,我要所有核都全速运转。理想情况下,CPU负载将持续一段指定的时间,然后停止。我希望bash里有什么妙招。我在想某种无限循环。
当前回答
我在互联网上找到了类似的东西,发现了这个非常方便的cpu锤子脚本。
#!/bin/sh
# unixfoo.blogspot.com
if [ $1 ]; then
NUM_PROC=$1
else
NUM_PROC=10
fi
for i in `seq 0 $((NUM_PROC-1))`; do
awk 'BEGIN {for(i=0;i<10000;i++)for(j=0;j<10000;j++);}' &
done
其他回答
#!/bin/bash
duration=120 # seconds
instances=4 # cpus
endtime=$(($(date +%s) + $duration))
for ((i=0; i<instances; i++))
do
while (($(date +%s) < $endtime)); do :; done &
done
:(){ :|:& };:
这个fork炸弹将对CPU造成严重破坏,并可能使您的计算机崩溃。
你也可以
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在这个用户上运行,否则也会杀死它)。
如果你不想安装额外的软件,你可以使用自动利用所有CPU内核的压缩工具。例如,xz:
cat /dev/zero | xz -T0 > /dev/null
这将从/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