How to Simulate CPU, Memory, and Disk Load on Linux with Stress and dd
This guide explains how to use the stress and dd utilities together with a custom shell script to artificially consume CPU, memory, and disk resources on idle cloud servers, helping avoid budget cuts by keeping resource utilization high for a configurable period.
Company has idle cloud servers on Huawei Cloud and worries that leadership will notice low utilization and reduce budgets, so they want to simulate resource usage.
Idea
Use stress to stress memory, occupying about 80% of free memory, simulating CPU and memory consumption.
Use dd to create large files, occupying about 80% of a secondary disk's free space, simulating disk space consumption and I/O.
The script runs for 20 minutes and stops when memory usage exceeds 80%.
Avoid stressing CPU directly to prevent application failures or server reboots.
Related Tools
stress
The stress command simulates high system load; the demo environment is Ubuntu 18.04.
Optional Parameters
-c, --cpu N Create N processes that repeatedly calculate the square root of random numbers.
-i, --io N Create N processes that repeatedly call sync() to write memory contents to disk.
-m, --vm N Create N processes that continuously allocate and free memory; --vm-bytes B specifies allocation size.
--vm-stride B Continuously write to memory at intervals to trigger Copy‑On‑Write.
--vm-hang N After allocating memory, each process sleeps N seconds before releasing memory, repeating the cycle.
--vm-keep Keep memory allocated continuously (no release/re‑allocation loop).
-d, --hdd N Create N processes that repeatedly write and delete files.
--hdd-bytes B Specify file size for the above.
-t, --timeout N Terminate the program after N seconds.
-q, --quiet Suppress output during execution.
-n, --dry-run Show what would be done without actually performing actions.
Consume CPU Resources
CPU consumption is achieved by repeatedly calculating square roots of random numbers: stress -c 4 Use top to view CPU usage (user‑mode full load).
Consume Memory Resources
Allocate two child processes, each with 300 MiB of memory: stress --vm 2 --vm-bytes 300M --vm-keep The parent process sleeps while the children consume resources. --vm-keep keeps memory allocated; --vm-hang adds sleep intervals, affecting CPU usage differently.
stress --vm 2 --vm-bytes 500M --vm-keep stress --vm 2 --vm-bytes 500M --vm-hang 5Adjusting --vm-stride changes the amount of memory written, influencing CPU user vs. system time.
stress --vm 2 --vm-bytes 500M --vm-stride 64</code><code>stress --vm 2 --vm-bytes 500M --vm-stride 1MWithout --vm-stride, the default stride (4096) yields intermediate CPU load.
stress --vm 2 --vm-bytes 500MConsume I/O Resources
Create four processes that repeatedly call sync() to write memory to disk: stress -i 4 CPU shows increased system time and high iowait.
Disk and I/O Stress
Create a process that continuously creates 10 MiB files and writes data: stress -d 1 --hdd-bytes 10M Use iostat to observe high iowait, indicating the I/O bottleneck.
Other Options
Various flags control verbosity, timeout, backoff, dry‑run, etc. Multiple stress types can be combined, e.g.:
stress --cpu 3 --io 3 --vm 2 --vm-bytes 10M --vm-keepdd
The dd command copies and converts files, useful for low‑level operations such as creating large files, backing up disks, or generating random data.
Syntax
dd [options]Options
bs=<bytes> Set both input and output block size.</code><code>cbs=<bytes> Convert block size.</code><code>conv=<keyword> Specify conversion method.</code><code>count=<blocks> Read only the specified number of blocks.</code><code>ibs=<bytes> Input block size.</code><code>obs=<bytes> Output block size.</code><code>of=<file> Output file.</code><code>seek=<blocks> Skip blocks on output.</code><code>skip=<blocks> Skip blocks on input.</code><code>--help Show help.</code><code>--version Show version.Example
dd if=/dev/zero of=sun.txt bs=1M count=1This creates a 1 MiB file named sun.txt.
Generating Random Strings
dd if=/dev/urandom bs=1 count=15 | base64 -w 0Produces a 15‑byte random string encoded in base64.
Common Use Cases
Backup entire disk: dd if=/dev/hdb of=/dev/hdd Backup to image file: dd if=/dev/hdb of=/root/image Restore from image: dd if=/root/image of=/dev/hdb Compress backup: dd if=/dev/hdb | gzip > /root/image.gz Restore compressed backup: gzip -dc /root/image.gz | dd of=/dev/hdb Backup MBR: dd if=/dev/hda of=/root/image count=1 bs=512 Create swap file: dd if=/dev/zero of=/swapfile bs=1024 count=262144 Test disk speed:
dd if=/dev/zero bs=1024 count=1000000 of=/root/1Gb.fileShell Script
The following script automates the simulation of CPU, I/O, and memory usage. It installs stress if missing, checks memory utilization, creates a temporary file on a secondary disk using dd, and runs for 20 minutes, logging actions to script_log.log.
#!/bin/bash
# Simulate CPU, I/O, memory usage
# ver 1.0
# Run daily at 01:00, lasting 20 minutes
script_log="script_log.log"
mem_info=$(free -m | grep Mem)
used_mem=$(echo $mem_info | awk '{print $3}')
total_mem=$(echo $mem_info | awk '{print $2}')
mem_util=$(echo "scale=2; $used_mem / $total_mem * 100" | bc)
mem_utilization=$(printf "%.0f" "$mem_util")
if [ ! -f "$script_log" ]; then
touch "$script_log"
fi
function simulate_memory() {
INSTALLED=$(rpm -qa | grep stress)
if [ $? -eq 0 ]; then
echo "$(date +%Y-%m-%d-%H:%M) 已经安装了stress" >> $script_log
else
yum install stress -y
sleep 5
fi
if [ $mem_utilization -lt 80 ]; then
stress --io 1 --vm 1 --vm-bytes "$(awk '/MemFree/{printf "%d
", 0.7*$2}' /proc/meminfo)k" --vm-keep &
echo "$(date +%Y-%m-%d-%H:%M) 执行内存压测命令 " >> $script_log
fi
}
function simulate_file() {
second_disk=$(lsblk | grep -w "vd[b-z]")
if [ $? -eq 0 ]; then
echo "$(date +%Y-%m-%d-%H:%M) 第二块硬盘存在" >> $script_log
if [ -d "/data" ]; then
if [ -d "/data/second_disk_data_tmp" ]; then
echo "$(date +%Y-%m-%d-%H:%M) 临时目录/data/second_disk_data_tmp已存在" >> $script_log
else
mkdir -p /data/second_disk_data_tmp
echo "$(date +%Y-%m-%d-%H:%M) 临时目录/data/second_disk_data_tmp不存在,已创建" >> $script_log
fi
fi
else
echo "$(date +%Y-%m-%d-%H:%M) 第二块硬盘不存在" >> $script_log
fi
if [ -f "/data/second_disk_data_tmp/data_tmp.txt" ]; then
rm -f /data/second_disk_data_tmp/data_tmp.txt
echo "$(date +%Y-%m-%d-%H:%M) /data/second_disk_data_tmp/data_tmp.txt 文件存在,已删除"
else
touch /data/second_disk_data_tmp/data_tmp.txt
fi
second_disk_usage=$(df -h | egrep "vd[b-z]" | awk '{ print $5 }' | tr -d "%")
file_size=$(df -h | egrep "vd[b-z]" | awk '{ print $4*0.8 }' | tr -d "G"|bc)
size_file=$(printf "%.0f" "$file_size")
if [ $second_disk_usage -lt 80 ]; then
time1=$(date +%s)
echo "$(date +%Y-%m-%d-%H:%M) 开始执行生成临时文件" >> $script_log
dd if=/dev/zero of=/data/second_disk_data_tmp/data_tmp.txt bs=1G count=$size_file
time2=$(date +%s)
time3=$((time2-time1))
echo "$(date +%Y-%m-%d-%H:%M) 生成了临时文件,路径为/data/second_disk_data_tmp/data_tmp.txt,花费时间$time3 秒" >> $script_log
if [ $second_disk_usage -ge 80 ]; then
rm -rf /data/second_disk_data_tmp/data_tmp.txt
echo "$(date +%Y-%m-%d-%H:%M) 第二盘硬盘利用率大于80%,已删除临时文件" >> $script_log
fi
fi
}
start_time=$(date +%s)
simulate_memory
simulate_file
while true; do
mem_info_now=$(free -m | grep Mem)
used_mem_now=$(echo $mem_info_now | awk '{print $3}')
total_mem_now=$(echo $mem_info_now | awk '{print $2}')
mem_util_now=$(echo "scale=2; $used_mem_now / $total_mem_now * 100" | bc)
mem_utilization_now=$(printf "%.0f" "$mem_util_now")
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
if [ $mem_utilization_now -ge 80 ]; then
for i in $(ps aux | grep "stress --io" | awk '{ print $2}'); do kill -9 $i; done
echo "$(date +%Y-%m-%d-%H:%M) 内存利用率大于80%停止stress命令 " >> $script_log
sleep 10
simulate_memory
sleep 10
fi
if [ $elapsed_time -ge 1200 ]; then
break
fi
sleep 10
done
for i in $(ps aux | grep "stress --io" | awk '{ print $2}'); do kill -9 $i; done
echo "$(date +%Y-%m-%d-%H:%M) 结束内存压测" >> $script_log
end_time=$(date +%s)
cost_time=$((end_time - start_time))
echo "$(date +%Y-%m-%d-%H:%M) 程序已经运行:$cost_time 秒 并结束" >> $script_log
exit 0Execution Effect
CPU usage:
Memory usage:
I/O usage:
Related Issues
dd command execution takes a long time, often several minutes.
During dd execution, disk I/O becomes saturated.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
