Module: ObjectStats

Defined in:
lib/utilrb/objectstats.rb

Constant Summary collapse

LIVE_OBJECTS_KEY =
:live_objects

Class Method Summary collapse

Class Method Details

.countObject

The count of objects currently allocated

It allocates no objects, which means that if a = ObjectStats.count b = ObjectStats.count then a == b



12
13
14
15
16
17
# File 'lib/utilrb/objectstats.rb', line 12

def self.count
    count = 0
    ObjectSpace.each_object { |obj| count += 1 }

  count
end

.count_by_class(threshold = nil) ⇒ Object

Returns a klass => count hash counting the currently allocated objects

It allocates 1 Hash, which is included in the count



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/utilrb/objectstats.rb', line 22

def self.count_by_class(threshold = nil)
    by_class = Hash.new(0)
    ObjectSpace.each_object { |obj|
        by_class[obj.class] += 1
        by_class
    }
    if threshold
        by_class.delete_if { |kl, count| count < threshold }
    end

    by_class
end

.profile(alive = false) ⇒ Object

Profiles how much objects has been allocated by the block. Returns a klass => count hash like count_by_class

If alive is true, then only live objects are returned.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/utilrb/objectstats.rb', line 41

def self.profile(alive = false)
  if alive
 GC.force
 profile do
    yield
    GC.force
 end
  end

    already_disabled = GC.disable
    before = count_by_class
  if ObjectSpace.respond_to?(:live_objects)
 before_live_objects = ObjectSpace.live_objects
  end
    yield
  if ObjectSpace.respond_to?(:live_objects)
 after_live_objects = ObjectSpace.live_objects
  end
    after  = count_by_class
  if after_live_objects
 before[LIVE_OBJECTS_KEY] = before_live_objects
 after[LIVE_OBJECTS_KEY]  = after_live_objects - 1 # correction for yield
  end
    GC.enable unless already_disabled

    after[Hash] -= 1 # Correction for the call of count_by_class
    profile = before.
        merge(after) { |klass, old, new| new - old }.
        delete_if { |klass, count| count == 0 }
end