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


当前回答

#!/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

其他回答

你也可以

dd if=/dev/zero of=/dev/null

要运行更多这样的程序,将负载放在更多的内核上,请尝试fork:

fulload() { dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null | dd if=/dev/zero of=/dev/null & }; fulload; read; killall dd

重复花括号中的命令的次数与您想要生成的线程数相同(这里是4个线程)。 简单的输入hit将停止它(只要确保没有其他dd在这个用户上运行,否则也会杀死它)。

我结合了一些答案,并添加了一种将压力扩展到所有可用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

为了增强dimba的答案并提供一些更可插拔的东西(因为我需要类似的东西)。我使用dd加载概念编写了以下内容

它将检查当前的内核,并创建相同数量的dd线程。 用Enter键开始和结束核心加载

#!/bin/bash

load_dd() {
    dd if=/dev/zero of=/dev/null
}

fulload() {
    unset LOAD_ME_UP_SCOTTY
    export cores="$(grep proc /proc/cpuinfo -c)"
    for i in $( seq 1 $( expr $cores - 1 ) )
      do
    export LOAD_ME_UP_SCOTTY="${LOAD_ME_UP_SCOTTY}$(echo 'load_dd | ')"
  done
        export LOAD_ME_UP_SCOTTY="${LOAD_ME_UP_SCOTTY}$(echo 'load_dd &')"
    eval ${LOAD_ME_UP_SCOTTY}
}

echo press return to begin and stop fullload of cores
  read
  fulload
  read
  killall -9 dd

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