File: object_binsize.rb

package info (click to toggle)
ruby-public-suffix 4.0.6%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 320 kB
  • sloc: ruby: 1,431; makefile: 10
file content (57 lines) | stat: -rw-r--r-- 1,504 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'tempfile'

# A very simple memory profiles that checks the full size of a variable
# by serializing into a binary file.
#
# Yes, I know this is very rough, but there are cases where ObjectSpace.memsize_of
# doesn't cooperate, and this is one of the possible workarounds.
#
# For certain cases, it works (TM).
class ObjectBinsize

  def measure(var, label: nil)
    dump(var, label: label)
  end

  def report(var, label: nil, padding: 10)
    file = measure(var, label: label)

    size = format_integer(file.size)
    name = label || File.basename(file.path)
    printf("%#{padding}s   %s\n", size, name)
  end

  private

  def dump(var, **args)
    file = Tempfile.new(args[:label].to_s)
    file.write(Marshal.dump(var))
    file
  ensure
    file.close
  end

  def format_integer(int)
    int.to_s.reverse.gsub(/...(?=.)/, '\&,').reverse
  end

end

if __FILE__ == $0
  prof = ObjectBinsize.new

  prof.report(nil, label: "nil")
  prof.report(false, label: "false")
  prof.report(true, label: "true")
  prof.report(0, label: "integer")
  prof.report("", label: "empty string")
  prof.report({}, label: "empty hash")
  prof.report({}, label: "empty array")

  prof.report({ foo: "1" }, label: "hash 1 item (symbol)")
  prof.report({ foo: "1", bar: 2 }, label: "hash 2 items (symbol)")
  prof.report({ "foo" => "1" }, label: "hash 1 item (string)")
  prof.report({ "foo" => "1", "bar" => 2 }, label: "hash 2 items (string)")

  prof.report("big string" * 200, label: "big string * 200")
end