我想在Linux机器上创建一个接近100%的负载。这是四核系统,我要所有核都全速运转。理想情况下,CPU负载将持续一段指定的时间,然后停止。我希望bash里有什么妙招。我在想某种无限循环。


当前回答

你也可以

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的方法:

#!/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
#!/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

如果你不想安装额外的软件,你可以使用自动利用所有CPU内核的压缩工具。例如,xz:

 cat /dev/zero | xz -T0 > /dev/null

这将从/dev/zero中获取无限的虚拟数据流,并使用系统中所有可用的内核对其进行压缩。

只需将这个坏小子粘贴到任何运行linux的服务器的SSH或控制台。您可以手动终止进程,但我只是在完成后关闭服务器,这样更快。

编辑:我已经更新了这个脚本,现在有一个定时器功能,这样就不需要杀死进程。

read -p "Please enter the number of minutes for test >" MINTEST && [[ $MINTEST == ?(-)+([0-9]) ]]; NCPU="$(grep -c ^processor /proc/cpuinfo)";  ((endtime=$(date +%s) + ($MINTEST*60))); NCPU=$((NCPU-1)); for ((i=1; i<=$NCPU; i++)); do while (($(date +%s) < $endtime)); do : ; done & done

使用这里提到的例子,以及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