Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created March 11, 2024 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedek6/c4084f7abf90bd3adf8afa0060562404 to your computer and use it in GitHub Desktop.
Save fedek6/c4084f7abf90bd3adf8afa0060562404 to your computer and use it in GitHub Desktop.
Bash profiler for app
#!/bin/bash
# Check if a PID was provided
if [ -z "$1" ]; then
echo "Usage: $0 <pid>"
exit 1
fi
PID=$1
OUTPUT_FILE="usage.txt"
# Function to get memory usage in MB on macOS
get_memory_macos() {
# Using `ps` to get the RSS (Resident Set Size) memory in bytes and converting to MB
echo "$(ps -o rss= -p $PID | awk '{print $1/1024 "MB"}')"
}
# Function to get memory usage in MB on Linux
get_memory_linux() {
# Using `ps` to get the RSS (Resident Set Size) memory in kilobytes and converting to MB
echo "$(ps -o rss= -p $PID | awk '{print $1/1024 "MB"}')"
}
# Main loop that records the usage every 5 seconds
while true; do
# Get CPU usage for the given PID
CPU_USAGE=$(ps -o %cpu= -p $PID)
# Get Memory usage for the given PID based on the operating system
MEMORY_USAGE=""
case "$(uname -s)" in
Darwin)
MEMORY_USAGE=$(get_memory_macos)
;;
Linux)
MEMORY_USAGE=$(get_memory_linux)
;;
*)
echo "Unsupported OS"
exit 1
;;
esac
# Get the current time
TIMESTAMP=$(date '+%H:%M:%S')
# Output to the file
echo "$TIMESTAMP CPU=${CPU_USAGE}%; MEMORY=${MEMORY_USAGE}" >> $OUTPUT_FILE
# Wait for 5 seconds
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment