Skip to content

Instantly share code, notes, and snippets.

@pricees
Created July 17, 2012 22:11
Show Gist options
  • Save pricees/3132488 to your computer and use it in GitHub Desktop.
Save pricees/3132488 to your computer and use it in GitHub Desktop.
Simple Benchmarking Ruby Script
#! /usr/bin/env ruby
require 'benchmark'
#
# Benchmarking cmd-line tool
#
#
# $ bench_it.rb "x = 5; 100.times { x * 5 }" "(1..1000).to_a.inject(:+)" --times=500
#
# EXAMPLE OUTPUT
#
# ==============
# [Trial 1], 500 time(s)
# "x = 5; 100.times { x * 5 }":
# ==============
# 0.020000 0.000000 0.020000 ( 0.023091)
#
#
#
# ==============
# [Trial 2], 500 time(s)
# "(1..1000).to_a.inject(:+)":
# ==============
# 0.100000 0.000000 0.100000 ( 0.101163)
#
def p_howto
puts <<-EOL
Accepts arbitrary number of blocks to benchmark:
$ bench_it.rb "x = 5; 100.times { x * 5 }" "(1..1000).to_a.inject(:+)"
use times option to run additional amount: "--times=[n]"
$ bench_it.rb "x = 5; 100.times { x * 5 }" "(1..1000).to_a.inject(:+)" --times=500
EOL
exit
end
#
# NOTE: This is a geto option parser. Don't tell
# the creator of Trollop (http://trollop.rubyforge.org/),
# he will be a lil angry
#
def many!
@many ||= begin
if opt = ARGV.grep(/--times=/).first
_, many = opt.split(/=/, 2).map &:to_i
ARGV.delete opt
end
many || 1
end
end
alias :many :many!
def p_header(code, trial)
str = %{\n==============\n[Trial #{trial}]}
str << %{, #{many} time(s)\n\t"#{code}":}
str << %{\n==============\n\n}
puts str
end
def get_lambda(code)
if many > 1
lambda { many.times { eval(code) } }
else
lambda { eval(code) }
end
end
def run!
many!
if ARGV.empty?
p_howto
exit
end
ARGV.each_with_index do |arg, i|
p_header(arg, i + 1)
lamb = get_lambda(arg)
puts Benchmark.measure { lamb.call }
end
end
run! if $0 == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment