Skip to content

Instantly share code, notes, and snippets.

@entity1991
Last active April 2, 2018 13:09
Show Gist options
  • Save entity1991/fc06b3cbac262239f7f6 to your computer and use it in GitHub Desktop.
Save entity1991/fc06b3cbac262239f7f6 to your computer and use it in GitHub Desktop.
Memory usage monitor
# Usage:
#
# peak_memory = track_memory do
# 1000000.times { |i| puts i }
# end
#
# puts peak_memory
# -> 845073
require 'thread'
class MemoryUsageMonitor
attr_reader :peak_memory
def initialize(frequency= 0.001)
@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
def self.voice
0 # may be calculated default memory usage of system
end
def peak_memory
@peak_memory - MemoryUsageMonitor.voice
end
end
module Kernel
def track_memory(&block)
mm = MemoryUsageMonitor.new
mm.start
yield
mm.stop
mm.peak_memory
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment