Script for testing CPU values and rules

I needed a script that would set a CPU usage value to a certain percent to test some static and forecasting alerts. All right for this to openAI. This script takes a parameter 1-100 and the script will attempt to keep the CPU value at that level.


# Check if usage percentage is passed as an argument
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <cpu_usage_percentage>"
    exit 1

# Desired CPU usage percentage

# Calculate sleep duration based on desired CPU usage
sleep_duration=$(awk "BEGIN {print (1 - $cpu_usage / 100) / ($cpu_usage / 100)}")

# Function to consume CPU up to the specified percentage
limit_cpu_usage() {
    while true; do
        # Start time
        start=$(date +%s.%N)

        # Busy loop for the duration of one second
        end=$(echo "$start + 1" | bc)
        while true; do
            current=$(date +%s.%N)
            check=$(echo "$current < $end" | bc)
            if [ "$check" -eq 0 ]; then
            : # No-op

        # Sleep for the calculated duration
        sleep $sleep_duration

# Run the function in the foreground

# Run the function in the background
# limit_cpu_usage &

1 Like

As an example of how I am using the script, we are running some tests on zooming in and out in our new charting package. We combine the severity timeline with the metric value.

Look good, but here’s your next challenge (tongue firmly in cheek):

1 Like

That looks like exactly what a 896 core machine should be used for!