Skip to content

Instantly share code, notes, and snippets.

@sxalexander
Created November 3, 2010 00:13

Revisions

  1. sxalexander created this gist Nov 3, 2010.
    48 changes: 48 additions & 0 deletions memusage.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    #!/usr/bin/env ruby

    # Memory usage script for WebFaction customers adapted to attempt to
    # draw username from the pwd
    # Nick Trew <[email protected]>
    # 2009-05-25

    # START CONFIG #
    require 'pathname'

    # Put your username here
    user = nil

    # if no username is defined, attempt to grab it from the pwd
    user ||= Pathname.pwd.dirname.to_s.split("/")[2]

    puts "Calculating memory usage for:" + user

    # Your memory limit (MB)
    # This can be found at http://www.webfaction.com/services/hosting
    # Enter "Application Memory" for whichever package you're on
    memory_limit = 80

    # END CONFIG #

    # Get the process list and split at newlines
    processes = `ps -u #{user} -o pid,rss,command`.split("\n")

    # We'll keep a running total of each process' memory usage here
    mem_count = 0

    # Loop through the processes
    processes.each do |line|
    # Split at the first space we encounter to separate the PID, RSS and COMMAND info
    pid, rss, cmd = line.strip.split(/\s/, 3)

    # Ignore the "PID RSS COMMAND" line (yes this is horrible)
    unless pid == 'PID' or rss == 'RSS' or cmd == 'COMMAND'
    # Add to the running total
    mem_count += rss.to_i

    # Output the process' memory usage and the associated command
    puts sprintf('PID %d using %.2f MB: %s', pid.to_i, rss.to_f / 1024, cmd)
    end
    end

    # Output the total memory usage for all the processes combined with the memory_limit specified above
    puts sprintf('Total memory usage: %.2f MB / %d MB', mem_count.to_f / 1024, memory_limit)