views:

56

answers:

1

Is there a mechanism for getting a reliable value for the number of active objects in a Ruby environment? I've found several approaches to produce an answer, and typically they resemble:

c = 0   
ObjectSpace.each_object { c += 1 }

The unfortunate problem with this is that there's a large number of Fixnum objects created simply to tabulate, not to mention some apparent overhead of the ObjectSpace method itself.

Of course one could filter results according to class and simply ignore Fixnum objects, but that seems to be an imperfect workaround as it makes presumptions about how each_object works.

I'd just like to find a mechanism for determining how much garbage is generated between one point during operation and another as the garbage collector can be turned off for diagnostic purposes to provide an accurate benchmark.

+1  A: 

I don't see a way to do it directly with Kernel or GC. Rails attempts to do this when benchmarking - see the source code for active_support/testing/performance.rb. Unfortunately, it looks like all of these methods require a patched Ruby interpreter.

The RubyProf docs might also be useful; this is one of the methods that Rails attempts to use. If you apply the patch (not sure where to find it) you should just be able to do:

RubyProf.measure_allocations; RubyProf::ALLOCATIONS

Brad