Class: TinyMem

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

Overview

a tiny memory measurement tool for linux and macos, measuring resident set size (rss) (i.e. total memory allocated and still in use).

ex:

# track a single measurement
TinyMem.measure do
  Array.new(100_000) { 'hello' }
end

=> [70568,  72732, 2164]

# track measurements over time
mem = TinyMem.new
mem.measure 'array_alloc' do
  Array.new(100_000) { 'hello' }
end

mem.measure 'nothing'

 > mem.stats
=> [
     ["array_alloc", 70568,  72732, 2164   ],
     ["nothing",     72744,  72744, 0      ]
   ]  ^label         ^before ^after ^diff ... in kilobytes

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTinyMem

Returns a new instance of TinyMem.



28
29
30
# File 'lib/tiny_mem.rb', line 28

def initialize
  @stats = []
end

Instance Attribute Details

#statsObject (readonly)

Returns the value of attribute stats.



26
27
28
# File 'lib/tiny_mem.rb', line 26

def stats
  @stats
end

Class Method Details

._memObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tiny_mem.rb', line 49

def self._mem
  case RUBY_PLATFORM
  when /linux/
    begin
      line = File.read("/proc/#{Process.pid}/status").match(/VmRSS:\s+(\d+)\s*/)
      line ? line[1].to_i : 'unknown'
    rescue Errno::ENOENT
      'error'
    end
  when /darwin/
    `ps -o rss= -p #{Process.pid}`.to_i
  else
    "#{RUBY_PLATFORM} not supported"
  end
end

.measureObject



40
41
42
43
44
45
46
47
# File 'lib/tiny_mem.rb', line 40

def self.measure
  pid = Process.pid
  before = _mem
  yield if block_given?
  after = _mem

  [before, after, after-before]
end

Instance Method Details

#measure(label) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/tiny_mem.rb', line 32

def measure(label)
  before, after, diff = TinyMem.measure do
                          yield if block_given?
                        end

  @stats << [label, before, after, diff]
end