PageRenderTime 9ms CodeModel.GetById 2ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/test-suite/ruby/swig_gc.rb

#
Ruby | 70 lines | 30 code | 9 blank | 31 comment | 4 complexity | 3951e3606361e692959bbcfee7b7354f MD5 | raw file
 1#!/usr/bin/env ruby
 2#
 3#
 4# VERY nice function from Robert Klemme to check memory leaks
 5# and check on what GC has collected since last call.
 6#
 7# Usage can be:
 8#
 9#     require 'swig_gc'
10#
11#     GC.stats
12#     # do some stuff..
13#     GC.start  # collect and report stats
14#     # do some more...
15#     GC.stats  # just report stats
16#
17# or:
18#
19#     require 'swig_gc'
20#
21#     GC.track_class = String  # track just String classes
22#     GC.stats
23#     # do some stuff..
24#     GC.start  # collect and report stats
25#     # do some more...
26#     GC.stats  # just report stats
27#
28# 
29# 
30# 
31#
32
33module GC
34
35  class << self
36      
37    attr          :last_stat
38    attr_accessor :track_class
39
40    alias :_start :start
41    
42    def start
43      _start
44      stats if $VERBOSE
45    end
46    
47    def stats
48      stats = Hash.new(0)
49      ObjectSpace.each_object {|o| stats[o.class] += 1}
50      
51      if track_class
52        v = stats[track_class]
53        printf "\t%-30s  %10d", track_class.to_s, v
54        if last_stat
55          printf " | delta %10d", (v - last_stat[track_class])
56        end
57        puts
58      else
59        stats.sort {|(k1,v1),(k2,v2)| v2 <=> v1}.each do |k,v|
60          printf "\t%-30s  %10d", k, v
61          printf " | delta %10d", (v - last_stat[k]) if last_stat
62          puts
63        end
64      end
65        
66      last_stat = stats
67    end
68  end
69  
70end