You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自制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" becomes echo 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 full ps command that fetches the right metric and suppresses headers.
  • No Timeout Enforcement: You track timeBefore but never check if the process exceeds MaxTime—the script will loop indefinitely if the command hangs.
  • Unchecked Process Status: The while true loop 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=0 but 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

  1. Array-Based Command Storage: Using Command=("$@") preserves all original arguments, even those with spaces or special characters. Running with "${Command[@]}" ensures correct argument passing.
  2. Process Health Checks: kill -0 "$pid" verifies if the PID exists without sending a signal, avoiding errors from dead processes.
  3. Hard Limits Enforcement: The loop actively checks for both timeouts and memory breaches, killing the process if either threshold is hit.
  4. Unit Consistency: Converts RSS (KB) to MB to match your MaxMemory input unit for clarity.
  5. Clean Error Handling: Redirects 2>/dev/null for commands that might fail (like ps on a dead PID) to keep output tidy.
  6. Exit Status Tracking: Captures the command's exit code so you can confirm if it completed successfully or was terminated early.
  7. Input Validation: Checks for minimum arguments and shows a usage message if the script is misused.

内容的提问来源于stack exchange,提问作者Remi.b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:38:28