How to create a CPU spike with a bash command

后端 未结 23 1221
小蘑菇
小蘑菇 2020-11-30 16:11

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

23条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 16:53

    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
    

提交回复
热议问题