Skip to content

Instantly share code, notes, and snippets.

@ngty
Created August 13, 2010 13:30
Show Gist options
  • Save ngty/522885 to your computer and use it in GitHub Desktop.
Save ngty/522885 to your computer and use it in GitHub Desktop.
# Usages:
#
# 1. Obtain benchmark results by repeating :spec by running the default number (5) of times
# $ rake benchmark[spec]
#
# 2. Obtain benchmark results by repeating :spec by running it 2 times
# $ rake benchmark[spec,2]
#
task :benchmark, :task, :times do |t, args|
times, task = (args.times || 5).to_i.method(:times), args.task
title = " ~ Benchmark Results for Task :#{task} ~ "
results = [%w{nth}, %w{user}, %w{system}, %w{total}, %w{real}]
# Running benchmarking & collecting results
require 'benchmark'
times.call do |i|
result = Benchmark.measure{ Rake::Task[task].execute }.to_s
user, system, total, real =
result.match(/^\s*(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)\s+\(\s*(\d+\.\d+)\)$/)[1..-1]
["##{i.succ}", user, system, total, real].each_with_index{|val, j| results[j] << val }
end
# Formatting benchmarking results
formatted_results = results.map do |rs|
width = rs.map(&:to_s).map(&:size).max
rs.map{|r| ' ' + r.ljust(width, ' ') }
end.transpose.map{|row| row.join }
# Showdown .. printout
line = '=' * ([title.size, formatted_results.map(&:size).max].max + 2)
puts [line, title, formatted_results.join("\n"), line].join("\n\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment