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


当前回答

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

其他回答

增加负载或消耗CPU 100%或X%

sha1sum /dev/zero &

在某些系统上,这将增加X%插槽的负载,在这种情况下,你必须多次运行相同的命令。

然后你可以通过输入命令查看CPU使用情况

top

释放负荷

killall sha1sum

只需将这个坏小子粘贴到任何运行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

你可以在这里下载一个程序

在Linux系统上轻松安装

./configure
make
make install

并在简单的命令行中启动它

stress -c 40

让所有的cpu(不管你有多少)都有40个线程,每个线程在随机生成的数字上运行复杂的根号计算。

您甚至可以定义程序的超时时间

stress -c 40 -timeout 10s

与提议的dd命令解决方案不同,dd命令主要处理IO,因此不会因为处理数据而真正使系统过载。

压力程序会使系统超负荷因为要处理计算。

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

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

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

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