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


当前回答

#!/bin/bash
while [ 1 ]
do
        #Your code goes here
done

其他回答

Dimba的dd if=/dev/zero of=/dev/null绝对是正确的,但值得一提的是验证cpu使用率最大化到100%。你可以用

ps -axro pcpu | awk '{sum+=$1} END {print sum}'

它要求每个进程的1分钟平均cpu使用量的ps输出,然后将它们与awk相加。虽然它是1分钟的平均值,但ps足够聪明,可以知道一个进程是否只运行了几秒钟,并相应地调整时间窗口。因此,您可以使用此命令立即查看结果。

我用过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

一个核心(不调用外部进程):

while true; do true; done

两个核心:

while true; do /bin/true; done

后者只会让我的两个都达到50%…

这将使两者都达到100%:

while true; do echo; done

我认为这个更简单。打开“终端”,输入以下命令并按“Enter”。

yes > /dev/null &

要充分利用现代CPU,一行命令是不够的,您可能需要重复该命令以耗尽所有CPU功率。

为了结束这一切,简单地说

killall yes

这个想法最初是在这里发现的,尽管它是为Mac用户设计的,但这应该也适用于*nix。