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


当前回答

我会把它分成两个脚本:

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

其他回答

无限循环也是我的想法。一个看起来很怪异的例子是:

while :; do :; done

(:与true相同,不执行任何操作并以0退出)

你可以在子shell中调用它并在后台运行。执行$num_cores次数应该就足够了。在睡眠到所需的时间后,您可以将它们全部杀死,使用jobs -p获得pid(提示:xargs)

您可以尝试测试加密算法的性能。

openssl speed -multi 4

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足够聪明,可以知道一个进程是否只运行了几秒钟,并相应地调整时间窗口。因此,您可以使用此命令立即查看结果。

我会把它分成两个脚本:

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

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

while true; do true; done

两个核心:

while true; do /bin/true; done

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

这将使两者都达到100%:

while true; do echo; done