1require 'objspace'
2
3#
4# purpose:
5#  Profile memory usage of each tests.
6#
7# usage:
8#   RUBY_TEST_ALL_PROFILE=true make test-all
9#
10# output:
11#   ./test_all_profile
12#
13# collected information:
14#   - ObjectSpace.memsize_of_all
15#   - GC.stat
16#   - /proc/self/statm (if it exists)
17#
18
19class MiniTest::Unit::TestCase
20  alias orig_run run
21
22  $test_all_profile_out = open('test_all_profile', 'w')
23  $test_all_profile_gc_stat_hash = {}
24
25  if FileTest.exist?('/proc/self/statm')
26    # for Linux (only?)
27    $test_all_profile_out.puts "name\tmemsize_of_all\t" +
28                                 (GC.stat.keys +
29                                  %w(size resident share text lib data dt)).join("\t")
30
31    def memprofile_test_all_result_result
32      "#{self.class}\##{self.__name__}\t" \
33      "#{ObjectSpace.memsize_of_all}\t" \
34      "#{GC.stat($test_all_profile_gc_stat_hash).values.join("\t")}\t" \
35      "#{File.read('/proc/self/statm').split(/\s+/).join("\t")}"
36    end
37  else
38    $test_all_profile_out.puts "name\tmemsize_of_alls\t" + GC.stat.keys.join("\t")
39    def memprofile_test_all_result_result
40      "#{self.class}\##{self.__name__}\t" \
41      "#{ObjectSpace.memsize_of_all}\t" \
42      "#{GC.stat($test_all_profile_gc_stat_hash).values.join("\t")}"
43    end
44  end
45
46  def run runner
47    result = orig_run(runner)
48    $test_all_profile_out.puts memprofile_test_all_result_result
49    $test_all_profile_out.flush
50    result
51  end
52end
53