我想在Linux机器上创建一个接近100%的负载。这是四核系统,我要所有核都全速运转。理想情况下,CPU负载将持续一段指定的时间,然后停止。我希望bash里有什么妙招。我在想某种无限循环。
当前回答
无限循环也是我的想法。一个看起来很怪异的例子是:
while :; do :; done
(:与true相同,不执行任何操作并以0退出)
你可以在子shell中调用它并在后台运行。执行$num_cores次数应该就足够了。在睡眠到所需的时间后,您可以将它们全部杀死,使用jobs -p获得pid(提示:xargs)
其他回答
#!/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
我用压力来做这种事情,你可以告诉它要最大化多少内核。它还允许对内存和磁盘施加压力。
例如,对2个核心施加压力60秒
压力——cpu 2——超时60
我会把它分成两个脚本:
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
虽然我迟到了,但这篇文章是谷歌搜索“在linux中生成负载”的顶级结果之一。
标记为solution的结果可以用来生成系统负载,我更倾向于使用sha1sum /dev/zero来对cpu内核施加负载。
其思想是从一个无限的数据流(例如。/dev/zero, /dev/urandom,…)该进程将尝试最大化一个cpu-core,直到进程终止。 要为更多内核生成负载,可以将多个命令连接在一起。
如。产生2个核心负荷: Sha1sum /dev/zero | Sha1sum /dev/zero
#!/bin/bash
while [ 1 ]
do
#Your code goes here
done