Class: MemoryUsage
- Inherits:
-
Object
- Object
- MemoryUsage
- Defined in:
- lib/memory_usage.rb
Overview
Class which has function for gathering memory stats. Should work on unix/linux and OS X Example usage at the bottom
Instance Method Summary collapse
-
#initialize ⇒ MemoryUsage
constructor
A new instance of MemoryUsage.
-
#refresh ⇒ Object
Recalculate Memory usage.
-
#report ⇒ Object
Display to stdout Error report.
-
#total ⇒ Object
Return total memory as a String.
Constructor Details
#initialize ⇒ MemoryUsage
Returns a new instance of MemoryUsage.
7 8 9 |
# File 'lib/memory_usage.rb', line 7 def initialize refresh end |
Instance Method Details
#refresh ⇒ Object
Recalculate Memory usage. stops have to call MemoryUsage.new
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/memory_usage.rb', line 12 def refresh #Based on: http://gist.github.com/290988 @total = 0.0 @usage = Array.new @max = {:pid=>0, :rss=>0, :command=>0} `ps -u $USER -o pid,rss,command`.split("\n").each do |p| p.strip! if p.match(/^\d/) p =~ /(\d+)\s+(\d+)\s+(.+)/ pid, rss, command = [$1, $2, $3] rss = rss.to_f @usage << {:pid=>pid, :rss=>(rss/1024), :command=>command } @total += rss/1024 if pid.to_s.size > @max[:pid] @max[:pid] = pid.to_s.size end if rss.to_s.size > @max[:rss] @max[:rss] = rss.to_s.size end if command.size > @max[:command] @max[:command] = command.size end #puts pid + (" %.2f MB " % (rss/1024)) + command end end @usage = @usage.sort_by { |process| process[:rss] } #puts "Your total usage: %.2f MB" % (total / 1024) end |
#report ⇒ Object
Display to stdout Error report
49 50 51 52 53 54 55 |
# File 'lib/memory_usage.rb', line 49 def report @usage.each do |x| #rjust string.rjust(min length) puts x[:pid].rjust( @max[:pid] ) + (" %.2f MB " % x[:rss]).rjust( @max[:rss]+3 ) + x[:command] end puts "Total Memory Usage: %.2f MB" % @total end |
#total ⇒ Object
Return total memory as a String
58 59 60 |
# File 'lib/memory_usage.rb', line 58 def total "%.2f" % @total end |