自制Bash内存与时间基准测试问题代码技术咨询
Fixing and Enhancing Your Bash Memory/Time Benchmark Script
Let's break down the issues in your current code and walk through a fully functional, robust version tailored to your benchmarking needs.
Key Problems in Your Original Code
- Broken Command Argument Handling: String concatenation (
Command="${Command} ${!i}") destroys quoted arguments (e.g.,echo "hello world"becomesecho hello world, losing the space-preserving context). Bash arrays are the correct way to store command arguments. - Incomplete Memory Check: Your
ps -o rs...line is truncated. To get accurate resident memory usage, you need a fullpscommand that fetches the right metric and suppresses headers. - No Timeout Enforcement: You track
timeBeforebut never check if the process exceedsMaxTime—the script will loop indefinitely if the command hangs. - Unchecked Process Status: The
while trueloop doesn't verify if the process is still running. If the command exits early, you'll keep trying to fetch memory from a dead PID, leading to errors. - Missing Peak Memory Logic: You initialized
MemoryPeak=0but didn't add code to update it when higher memory usage is detected. - Unquoted Variable Expansion: Variables like
${Command}break when arguments contain spaces; array expansion is far safer.
Improved, Complete Benchmark Script
#!/bin/bash # Validate input arguments if [ $# -lt 3 ]; then echo "Usage: $0 <max_memory_mb> <max_time_sec> <command> [args...]" exit 1 fi MaxMemory="$1" MaxTime="$2" shift 2 # Store command + arguments in an array (preserves spaces/special characters) Command=("$@") echo -e "MaxMemory = ${MaxMemory} MB\nMaxTime = ${MaxTime} seconds\nCommand = ${Command[*]}" # Run command in background "${Command[@]}" & pid=$! echo "Process ID: ${pid}" # Initialize monitoring variables MemoryPeak=0 timeBefore=$(date +"%s") process_running=true while $process_running; do # Check if process is still alive (no signal sent, just existence check) if ! kill -0 "$pid" 2>/dev/null; then process_running=false break fi # Get current resident memory (in KB), suppress errors if process exits mid-check mem=$(ps -o rss= -p "$pid" 2>/dev/null | tr -d ' ') # Update peak memory (convert KB to MB to match input unit) if [ -n "$mem" ]; then mem_mb=$((mem / 1024)) if [ "$mem_mb" -gt "$MemoryPeak" ]; then MemoryPeak="$mem_mb" fi fi # Check for timeout timeNow=$(date +"%s") elapsed=$((timeNow - timeBefore)) if [ "$elapsed" -ge "$MaxTime" ]; then echo "Timeout reached (${MaxTime}s), killing process ${pid}" kill "$pid" 2>/dev/null wait "$pid" 2>/dev/null process_running=false break fi # Check for memory limit breach if [ "$MemoryPeak" -ge "$MaxMemory" ]; then echo "Memory limit exceeded (${MaxMemory}MB peak: ${MemoryPeak}MB), killing process ${pid}" kill "$pid" 2>/dev/null wait "$pid" 2>/dev/null process_running=false break fi # Reduce CPU usage with a short sleep (adjust duration as needed) sleep 0.1 done # Capture command exit status wait "$pid" 2>/dev/null exit_status=$? # Final benchmark summary echo -e "\nBenchmark Results:" echo "Elapsed Time: $(( $(date +"%s") - timeBefore )) seconds" echo "Peak Memory Usage: ${MemoryPeak} MB" echo "Command Exit Status: ${exit_status}"
What This Fixes & Adds
- Array-Based Command Storage: Using
Command=("$@")preserves all original arguments, even those with spaces or special characters. Running with"${Command[@]}"ensures correct argument passing. - Process Health Checks:
kill -0 "$pid"verifies if the PID exists without sending a signal, avoiding errors from dead processes. - Hard Limits Enforcement: The loop actively checks for both timeouts and memory breaches, killing the process if either threshold is hit.
- Unit Consistency: Converts RSS (KB) to MB to match your
MaxMemoryinput unit for clarity. - Clean Error Handling: Redirects
2>/dev/nullfor commands that might fail (likepson a dead PID) to keep output tidy. - Exit Status Tracking: Captures the command's exit code so you can confirm if it completed successfully or was terminated early.
- Input Validation: Checks for minimum arguments and shows a usage message if the script is misused.
内容的提问来源于stack exchange,提问作者Remi.b
相关产品推荐
相关产品推荐

