Class: Analyzer::Rss

Inherits:
Object
  • Object
show all
Defined in:
lib/analyzer/rss.rb

Constant Summary collapse

KB_TO_BYTE =

2**10 = 1024

1024
MB_TO_BYTE =

1024**2 = 1_048_576

1_048_576
GB_TO_BYTE =

1024**3 = 1_073_741_824

1_073_741_824
CONVERSION =
{ "kb" => KB_TO_BYTE, "mb" => MB_TO_BYTE, "gb" => GB_TO_BYTE }

Instance Method Summary collapse

Constructor Details

#initialize(pid = Process.pid) ⇒ Rss

Returns a new instance of Rss.



11
12
13
14
15
# File 'lib/analyzer/rss.rb', line 11

def initialize(pid = Process.pid)
  @pid          = pid
  @status_file  = "/proc/#{@pid}/status"
  @linux        = File.exists?(@status_file)
end

Instance Method Details

#bytesObject



17
18
19
# File 'lib/analyzer/rss.rb', line 17

def bytes
  @linux ? (linux_status_memory || ps_memory) : ps_memory
end

#inspectObject



21
22
23
# File 'lib/analyzer/rss.rb', line 21

def inspect
  "#<#{self.class}:0x%08x @bytes=#{bytes}>" % (object_id * 2)
end

#linux_status_memoryObject

linux stores memory info in a file “/proc/#@pid/status” If it’s available it uses less resources than shelling out to ps



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/analyzer/rss.rb', line 27

def linux_status_memory
  line = File.new(@status_file).each_line.detect { |l| l.start_with?('VmRSS'.freeze) }
  if line
    line = line.split(nil)
    if line.length == 3
      CONVERSION[line[1].downcase!] * line[2].to_i
    end
  end
rescue Errno::EACCES, Errno::ENOENT
  0
end

#ps_memoryObject

Pull memory from ‘ps` command, takes more resources and can freeze in low memory situations



41
42
43
# File 'lib/analyzer/rss.rb', line 41

def ps_memory
  KB_TO_BYTE * BigDecimal(`ps -o rss= -p #{@pid}`)
end