我想在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
#!/bin/bash
while [ 1 ]
do
#Your code goes here
done
无限循环也是我的想法。一个看起来很怪异的例子是:
while :; do :; done
(:与true相同,不执行任何操作并以0退出)
你可以在子shell中调用它并在后台运行。执行$num_cores次数应该就足够了。在睡眠到所需的时间后,您可以将它们全部杀死,使用jobs -p获得pid(提示:xargs)
:(){ :|:& };:
这个fork炸弹将对CPU造成严重破坏,并可能使您的计算机崩溃。
使用这里提到的例子,以及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
推荐文章
- 如何从终端机发送电子邮件?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 在Bash中模拟do-while循环
- 在Bash中将输出赋给变量
- 在SSH会话中查找客户端的IP地址
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- 如何在Mac OS X 10.6中使硬件发出哔哔声
- Linux删除大小为0的文件
- 从Docker容器获取环境变量
- Spring引导应用程序作为服务
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?
- Windows和Linux上的c++编译:ifdef开关
- 如何循环通过一个目录递归删除具有某些扩展名的文件