我想在Linux机器上创建一个接近100%的负载。这是四核系统,我要所有核都全速运转。理想情况下,CPU负载将持续一段指定的时间,然后停止。我希望bash里有什么妙招。我在想某种无限循环。
当前回答
我结合了一些答案,并添加了一种将压力扩展到所有可用cpu的方法:
#!/bin/bash
function infinite_loop {
while [ 1 ] ; do
# Force some computation even if it is useless to actually work the CPU
echo $((13**99)) 1>/dev/null 2>&1
done
}
# Either use environment variables for DURATION, or define them here
NUM_CPU=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
PIDS=()
for i in `seq ${NUM_CPU}` ;
do
# Put an infinite loop on each CPU
infinite_loop &
PIDS+=("$!")
done
# Wait DURATION seconds then stop the loops and quit
sleep ${DURATION}
# Parent kills its children
for pid in "${PIDS[@]}"
do
kill $pid
done
其他回答
我会把它分成两个脚本:
infinite_loop。bash:
#!/bin/bash
while [ 1 ] ; do
# Force some computation even if it is useless to actually work the CPU
echo $((13**99)) 1>/dev/null 2>&1
done
cpu_spike。bash:
#!/bin/bash
# Either use environment variables for NUM_CPU and DURATION, or define them here
for i in `seq ${NUM_CPU}` : do
# Put an infinite loop on each CPU
infinite_loop.bash &
done
# Wait DURATION seconds then stop the loops and quit
sleep ${DURATION}
killall infinite_loop.bash
:(){ :|:& };:
这个fork炸弹将对CPU造成严重破坏,并可能使您的计算机崩溃。
你可以在这里下载一个程序
在Linux系统上轻松安装
./configure
make
make install
并在简单的命令行中启动它
stress -c 40
让所有的cpu(不管你有多少)都有40个线程,每个线程在随机生成的数字上运行复杂的根号计算。
您甚至可以定义程序的超时时间
stress -c 40 -timeout 10s
与提议的dd命令解决方案不同,dd命令主要处理IO,因此不会因为处理数据而真正使系统过载。
压力程序会使系统超负荷因为要处理计算。
我用过bc(二进制计算器),用一大堆小数求圆周率。
$ for ((i=0;i<$NUMCPU;i++));do
echo 'scale=100000;pi=4*a(1);0' | bc -l &
done ;\
sleep 4; \
killall bc
NUMCPU (Linux下):
$ NUMCPU=$(grep $'^processor\t*:' /proc/cpuinfo |wc -l)
这个方法很强大,但似乎对系统友好,因为我从未使用过这个方法导致系统崩溃。
使用这里提到的例子,以及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