Skip to content

Instantly share code, notes, and snippets.

@kelapure
Last active December 5, 2018 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kelapure/f24a0e27aa12f1d3364a93b5289e7ec2 to your computer and use it in GitHub Desktop.
Save kelapure/f24a0e27aa12f1d3364a93b5289e7ec2 to your computer and use it in GitHub Desktop.
Poor man's profiler for Ruby
# chp2/wrapper.rb
require ​"json"
require ​"benchmark"
def​ measure(&block)
no_gc = (ARGV[0] == ​"--no-gc"​)
​if​ no_gc
GC.disable
​else
​# collect memory allocated during library loading
​# and our own code before the measurement
GC.start
​end
memory_before = `ps -o rss= -p #{Process.pid}`.to_i/1024
gc_stat_before = GC.stat
time = Benchmark.realtime ​do
​yield
​end
puts ObjectSpace.count_objects
​unless​ no_gc
GC.start(full_mark: true, immediate_sweep: true, immediate_mark: false)
​end
puts ObjectSpace.count_objects
gc_stat_after = GC.stat
memory_after = `ps -o rss= -p #{Process.pid}`.to_i/1024
puts({
RUBY_VERSION => {
gc: no_gc ? ​'disabled'​ : ​'enabled'​,
time: time.round(2),
gc_count: gc_stat_after[:count] - gc_stat_before[:count],
memory: ​"%d MB"​ % (memory_after - memory_before)
}
}.to_json)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment