Skip to content

Instantly share code, notes, and snippets.

@universal
Forked from workmad3/bm.rb
Created February 6, 2015 11:57
Show Gist options
  • Select an option

  • Save universal/2abd8985a241f31140a0 to your computer and use it in GitHub Desktop.

Select an option

Save universal/2abd8985a241f31140a0 to your computer and use it in GitHub Desktop.
require 'benchmark'
hsh = {}
1000.times {|i| hsh[i.to_s] = i.succ.to_s}
Benchmark.bm do |x|
x.report("Hash[]") {1000.times{Hash[hsh.values.zip(hsh.keys)]}}
x.report("invert") {1000.times{hsh.invert}}
x.report("each_with_object") {1000.times{hsh.each_with_object({}){|(k,v),h| h[v] = k}}}
end
require 'ruby-prof'
require 'fileutils'
# memory, allocations are supposedly to work with patched ruby, but somehow don't
# rvm install 2.1.5 --patch railsexpress -n railsexpress
{
"RubyProf::PROCESS_TIME" => RubyProf::PROCESS_TIME,
"RubyProf::WALL_TIME" => RubyProf::WALL_TIME,
"RubyProf::CPU_TIME" => RubyProf::CPU_TIME,
"RubyProf::ALLOCATIONS" => RubyProf::ALLOCATIONS,
"RubyProf::MEMORY" => RubyProf::MEMORY,
"RubyProf::GC_RUNS" => RubyProf::GC_RUNS,
"RubyProf::GC_TIME" => RubyProf::GC_TIME,
"RubyProf::ALLOCATIONS" => RubyProf::ALLOCATIONS}.each do |mode_name, mode|
RubyProf.measure_mode = mode
results = {}
results["hash_square"] = RubyProf.profile do
1000.times{Hash[hsh.values.zip(hsh.keys)]}
end
results["invert"] = RubyProf.profile do
1000.times{hsh.invert}
end
results["each_with_object"] = RubyProf.profile do
1000.times{hsh.each_with_object({}){|(k,v),h| h[v] = k}}
end
results.each do |name, result|
FileUtils.mkdir_p("output/#{name}")
printer = RubyProf::MultiPrinter.new result
printer.print path: "output/#{name}", profile: mode_name.to_s.downcase.gsub("::", "_")
end
end
user system total real
Hash[] 0.270000 0.000000 0.270000 ( 0.269190)
invert 0.200000 0.000000 0.200000 ( 0.197517)
each_with_object 0.340000 0.000000 0.340000 ( 0.340221)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment