Skip to content

Instantly share code, notes, and snippets.

@carloslopes
Created May 11, 2015 19:38
Show Gist options
  • Save carloslopes/e3165201ea1c8dc4744f to your computer and use it in GitHub Desktop.
Save carloslopes/e3165201ea1c8dc4744f to your computer and use it in GitHub Desktop.
Ruby Process Memory Usage Monitor
require_relative 'lib/memory_usage_monitor'
mm = MemoryUsageMonitor.new
mm.start
sum = 0
items = []
5_000_000.times do |n|
sum += n
items << n.to_s if rand > 0.8
end
mm.stop
puts "Peak memory: #{mm.peak_memory/1024} MB"
require 'thread'
class MemoryUsageMonitor
attr_reader :peak_memory
def initialize(frequency: 0.25)
@frequency = frequency
@peak_memory = 0
end
def start
@thread = Thread.new do
while true do
memory = `ps -o rss -p #{Process::pid}`.chomp.split("\n").last.strip.to_i
@peak_memory = [memory, @peak_memory].max
sleep @frequency
end
end
end
def stop
Thread.kill(@thread)
end
end
@blvrd
Copy link

blvrd commented Jul 1, 2016

So helpful. Thank you Carlos!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment