3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby] メモリ使用量を計測する

Last updated at Posted at 2021-04-08

方法

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
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?