How to create a CPU spike with a bash command

LinuxBashLoadCpu

Linux Problem Overview


I want to create a near 100% load on a Linux machine. It's quad core system and I want all cores going full speed. Ideally, the CPU load would last a designated amount of time and then stop. I'm hoping there's some trick in bash. I'm thinking some sort of infinite loop.

Linux Solutions


Solution 1 - Linux

I use stress for this kind of thing, you can tell it how many cores to max out.. it allows for stressing memory and disk as well.

Example to stress 2 cores for 60 seconds

stress --cpu 2 --timeout 60

Solution 2 - Linux

You can also do

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

To run more of those to put load on more cores, try to fork it:

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

Repeat the command in the curly brackets as many times as the number of threads you want to produce (here 4 threads). Simple enter hit will stop it (just make sure no other dd is running on this user or you kill it too).

Solution 3 - Linux

I think this one is simpler. Open Terminal and type the following and press Enter.

yes > /dev/null &

To fully utilize modern CPUs, one line is not enough, you may need to repeat the command to exhaust all the CPU power.

To end all of this, simply put

killall yes

The idea was originally found here, although it was intended for Mac users, but this should work for *nix as well.

Solution 4 - Linux

Although I'm late to the party, this post is among the top results in the google search "generate load in linux".

The result marked as solution could be used to generate a system load, i'm preferring to use sha1sum /dev/zero to impose a load on a cpu-core.

The idea is to calculate a hash sum from an infinite datastream (eg. /dev/zero, /dev/urandom, ...) this process will try to max out a cpu-core until the process is aborted. To generate a load for more cores, multiple commands can be piped together.

eg. generate a 2 core load: sha1sum /dev/zero | sha1sum /dev/zero

Solution 5 - Linux

To load 3 cores for 5 seconds:

seq 3 | xargs -P0 -n1 timeout 5 yes > /dev/null

This results in high kernel (sys) load from the many write() system calls.

If you prefer mostly userland cpu load:

seq 3 | xargs -P0 -n1 timeout 5 md5sum /dev/zero

If you just want the load to continue until you press Ctrl-C:

seq 3 | xargs -P0 -n1 md5sum /dev/zero

Solution 6 - Linux

One core (doesn't invoke external process):

while true; do true; done

Two cores:

while true; do /bin/true; done

The latter only makes both of mine go to ~50% though...

This one will make both go to 100%:

while true; do echo; done

Solution 7 - Linux

Here is a program that you can download Here

Install easily on your Linux system

./configure
make
make install

and launch it in a simple command line

stress -c 40

to stress all your CPUs (however you have) with 40 threads each running a complex sqrt computation on a ramdomly generated numbers.

You can even define the timeout of the program

stress -c 40 -timeout 10s

unlike the proposed solution with the dd command, which deals essentially with IO and therefore doesn't really overload your system because working with data.

The stress program really overloads the system because dealing with computation.

Solution 8 - Linux

An infinite loop is the idea I also had. A freaky-looking one is:

while :; do :; done

(: is the same as true, does nothing and exits with zero)

You can call that in a subshell and run in the background. Doing that $num_cores times should be enough. After sleeping the desired time you can kill them all, you get the PIDs with jobs -p (hint: xargs)

Solution 9 - Linux

:(){ :|:& };:

This fork bomb will cause havoc to the CPU and will likely crash your computer.

Solution 10 - Linux

I would split the thing in 2 scripts :

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

Solution 11 - Linux

to increase load or consume CPU 100% or X%

sha1sum /dev/zero &

on some system this will increase the load in slots of X%, in that case you have to run the same command multiple time.

then you can see CPU uses by typing command

top

to release the load

killall sha1sum

Solution 12 - Linux

cat /dev/urandom > /dev/null

Solution 13 - Linux

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

Solution 14 - Linux

I've used bc (binary calculator), asking them for PI with a big lot of decimals.

$ for ((i=0;i<$NUMCPU;i++));do
    echo 'scale=100000;pi=4*a(1);0' | bc -l &
    done ;\
    sleep 4; \
    killall bc

with NUMCPU (under Linux):

$ NUMCPU=$(grep $'^processor\t*:' /proc/cpuinfo |wc -l)

This method is strong but seem system friendly, as I've never crashed a system using this.

Solution 15 - Linux

#!/bin/bash
while [ 1 ]
do
        #Your code goes here
done

Solution 16 - Linux

I went through the Internet to find something like it and found this very handy cpu hammer script.

#!/bin/sh

# unixfoo.blogspot.com

if [ $1 ]; then
    NUM_PROC=$1
else
    NUM_PROC=10
fi

for i in `seq 0 $((NUM_PROC-1))`; do
    awk 'BEGIN {for(i=0;i<10000;i++)for(j=0;j<10000;j++);}' &
done

Solution 17 - Linux

Using examples mentioned here, but also help from IRC, I developed my own CPU stress testing script. It uses a subshell per thread and the endless loop technique. You can also specify the number of threads and the amount of time interactively.

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

Solution 18 - Linux

Utilizing ideas here, created code which exits automatically after a set duration, don't have to kill processes --

#!/bin/bash
echo "Usage : ./killproc_ds.sh 6 60  (6 threads for 60 secs)"

# Define variables
NUM_PROCS=${1:-6} #How much scaling you want to do
duration=${2:-20}    # seconds

function infinite_loop {
endtime=$(($(date +%s) + $duration))
while (($(date +%s) < $endtime)); do
	#echo $(date +%s)
	echo $((13**99)) 1>/dev/null 2>&1
	$(dd if=/dev/urandom count=10000 status=none| bzip2 -9 >> /dev/null) 2>&1 >&/dev/null
done
echo "Done Stressing the system - for thread $1"
}


echo Running for duration $duration secs, spawning $NUM_PROCS threads in background
for i in `seq ${NUM_PROCS}` ;
do
# Put an infinite loop
    infinite_loop $i  &
done

Solution 19 - Linux

This does a trick for me:

bash -c 'for (( I=100000000000000000000 ; I>=0 ; I++ )) ; do echo $(( I+I*I )) & echo $(( I*I-I )) & echo $(( I-I*I*I )) & echo $(( I+I*I*I )) ; done' &>/dev/null

and it uses nothing except bash.

Solution 20 - Linux

To enhance dimba's answer and provide something more pluggable (because i needed something similar). I have written the following using the dd load-up concept :D

It will check current cores, and create that many dd threads. Start and End core load with 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

Solution 21 - Linux

Dimba's dd if=/dev/zero of=/dev/null is definitely correct, but also worth mentioning is verifying maxing the cpu to 100% usage. You can do this with

ps -axro pcpu | awk '{sum+=$1} END {print sum}'

This asks for ps output of a 1-minute average of the cpu usage by each process, then sums them with awk. While it's a 1 minute average, ps is smart enough to know if a process has only been around a few seconds and adjusts the time-window accordingly. Thus you can use this command to immediately see the result.

Solution 22 - Linux

I combined some of the answers and added a way to scale the stress to all available cpus:

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

Solution 23 - Linux

Just paste this bad boy into the SSH or console of any server running linux. You can kill the processes manually, but I just shutdown the server when I'm done, quicker.

Edit: I have updated this script to now have a timer feature so that there is no need to kill the processes.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUser1View Question on Stackoverflow
Solution 1 - LinuxDavidView Answer on Stackoverflow
Solution 2 - LinuxdimbaView Answer on Stackoverflow
Solution 3 - Linuxuser1147015View Answer on Stackoverflow
Solution 4 - LinuxMitmsView Answer on Stackoverflow
Solution 5 - LinuxJames ScrivenView Answer on Stackoverflow
Solution 6 - LinuxL̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳View Answer on Stackoverflow
Solution 7 - LinuxFopa Léon ConstantinView Answer on Stackoverflow
Solution 8 - LinuxMarianView Answer on Stackoverflow
Solution 9 - LinuxJeff GoldsteinView Answer on Stackoverflow
Solution 10 - LinuxFredView Answer on Stackoverflow
Solution 11 - Linux44kksharmaView Answer on Stackoverflow
Solution 12 - LinuxEvgenyView Answer on Stackoverflow
Solution 13 - LinuxDennis WilliamsonView Answer on Stackoverflow
Solution 14 - LinuxF. HauriView Answer on Stackoverflow
Solution 15 - LinuxSeckoView Answer on Stackoverflow
Solution 16 - LinuxIshtiaq AhmedView Answer on Stackoverflow
Solution 17 - LinuxMirceaKitsuneView Answer on Stackoverflow
Solution 18 - LinuxDhirajView Answer on Stackoverflow
Solution 19 - LinuxZyXView Answer on Stackoverflow
Solution 20 - LinuxknopeView Answer on Stackoverflow
Solution 21 - LinuxjeremysprofileView Answer on Stackoverflow
Solution 22 - LinuxjoecksView Answer on Stackoverflow
Solution 23 - LinuxGarretSidzakaView Answer on Stackoverflow