Skip to content

A pattern for measuring memory use of a block of code #53

@jjb

Description

@jjb

What do you think of this pattern for measuring memory use of a block of code? Assume:

  • single-threaded process, so the block of code is the only thing doing work
  • the code is known to last 10+ seconds
require 'get_process_mem'

GPM = GetProcessMem.new

def measure_memory_use
  start = GPM.bytes
  samples = []
  shutdown = false

  t = Thread.new do
    loop do
      break if shutdown
      sleep 0.1
      samples << GPM.bytes
    end
  end

  yield

  shutdown=true
  samples.max - start
end

class MyClass
  def initialize(x)
    @x = x
  end
end

puts "warmup"
a = []
20_000_000.times{a<<MyClass.new(rand)}
a=nil
puts

#3.times{GC.start}
#GC.compact

Process.warmup

puts "1 million"
puts measure_memory_use{ a=[]; 1_000_000.times{a<<MyClass.new(rand)}; sleep 1 }

Process.warmup

puts "2 million"
puts measure_memory_use{ a=[]; 2_000_000.times{a<<MyClass.new(rand)}; sleep 1 }
➔ ruby code.rb
warmup

1 million
48316416
2 million
96649216

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions