Skip to content

Instantly share code, notes, and snippets.

@jmkoni
Created May 26, 2015 19:34
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 jmkoni/36ec8f31b0a2ebd79691 to your computer and use it in GitHub Desktop.
Save jmkoni/36ec8f31b0a2ebd79691 to your computer and use it in GitHub Desktop.
Benchmark script from Ruby Performance Optimization (https://pragprog.com/book/adrpo/ruby-performance-optimization)
require "json"
require "benchmark"
class Measure
def self.run(&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
gc_stat_after = GC.stat
GC.start unless no_gc
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: "%dM" % (memory_after - memory_before)
}
}.to_json)
end
end
@jmkoni
Copy link
Author

jmkoni commented Dec 9, 2015

Call it like this:

Measure.run do
  #whatever code you want to test
end

The output will look like this:

{"2.2.2":{"gc":"enabled","time":0.04,"gc_count":0,"memory":"0M"}}

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