方法
ObjectSpace.memsize_of_all を使う。
require 'objspace'
def measure_memsize_before_and_after
# メモリ使用量をなるべく正確に計測するために、事前に GC を実行しておく。
GC.start
before = ObjectSpace.memsize_of_all
yield
after = ObjectSpace.memsize_of_all
[before, after]
end
使用例
def fibonacci_numbers
Enumerator.new do |y|
n, m = 0, 1
loop do
y << n
n, m = m, n + m
end
end
end
require 'active_support/all'
before_memsize, after_memsize = measure_memsize_before_and_after { fibonacci_numbers.first(100) }
puts "[Before] memsize_of_all: #{(before_memsize / 1_024).to_s(:delimited)} KB"
# [Before] memsize_of_all: 4,908 KB
puts "[After] memsize_of_all: #{(after_memsize / 1_024).to_s(:delimited)} KB"
# [After] memsize_of_all: 4,915 KB
before_memsize, after_memsize = measure_memsize_before_and_after { fibonacci_numbers.first(100_000) }
puts "[Before] memsize_of_all: #{(before_memsize / 1_024).to_s(:delimited)} KB"
# [Before] memsize_of_all: 5,084 KB
puts "[After] memsize_of_all: #{(after_memsize / 1_024).to_s(:delimited)} KB"
# [After] memsize_of_all: 433,674 KB