Skip to content

Instantly share code, notes, and snippets.

@pvdb
Last active December 10, 2015 07:08
Show Gist options
  • Save pvdb/4398712 to your computer and use it in GitHub Desktop.
Save pvdb/4398712 to your computer and use it in GitHub Desktop.
a multi-dimensional Ruby benchmark script :-)
#!/usr/bin/env ruby
#
# NAME
#
# benchmark.rb -- a multi-dimensional Ruby benchmark script :-)
#
# DESCRIPTION
#
# a customized Ruby "interpreter" that benchmarks
# other Ruby scripts... by default, both resident
# memory usage and elapsed time are measured, and
# reported to the console; adding other measures
# and changing the reporting units is easy to do!
#
# USAGE
#
# Ensure `benchmark.rb` has execute perms:
#
# chmod a+x benchmark.rb
#
# In order to benchmark another Ruby script,
# change its shebang line to something like:
#
# #!/usr/bin/env ./benchmark.rb
#
# Alternatively run this script directly by
# by adding the Ruby script as an argument:
#
# ./benchmark.rb some_other_script.rb
#
# NOTES
#
# the elapsed real time can be much better measured using
# Ruby's standard "benchmark" library; to illustrate how
# multiple measures can be nested and reported, though,
# this script measures it directly, albeit more naively
#
# the real memory (resident set) size of the process (in 1024 byte units).
def Process.rss ; `ps -o rss= -p #{Process.pid}`.chomp.to_i ; end
# determine a measure (by calling the proc)
# before & after running the block of code
def measure measure_name, measure_proc
before = measure_proc.call ; warn "(#{__FILE__}) #{measure_name} - before: #{before}" if $DEBUG
yield if block_given?
after = measure_proc.call ; warn "(#{__FILE__}) #{measure_name} - after: #{after}" if $DEBUG
[before, after].tap { |result|
class << result
alias_method :before, :first
alias_method :after, :last
end
}
end
# default measures: resident memory and elapsed time
rss = tms = nil
# do it...
rss = measure("RSS", -> { Process.rss }) do
tms = measure("Time", -> { Time.now }) do
# GC.disable # uncomment to get "true" picture of memory usage/increase
warn "(#{__FILE__}) running '#{ARGV.first}'" if $DEBUG
load ARGV.shift # run the actual Ruby script
end
end
# print out the measures...
warn ""
warn "(#{__FILE__}) Memory usage/increase - %s kilobytes" % (rss.after - rss.before)
warn "(#{__FILE__}) Elapsed real time - %.2f seconds" % (tms.after - tms.before)
# That's all, Folks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment