Skip to content

Instantly share code, notes, and snippets.

@brainopia
Created November 19, 2011 22:39
Show Gist options
  • Save brainopia/1379471 to your computer and use it in GitHub Desktop.
Save brainopia/1379471 to your computer and use it in GitHub Desktop.
initial draft of capistrano benchmarker
require 'benchmark'
module Capistrano::Benchmark
def self.included(base)
base.class_eval do
alias execute_task_without_benchmark execute_task
alias execute_task execute_task_with_benchmark
end
end
def self.print
Report.print Node::TOPLEVEL
end
def execute_task_with_benchmark(task)
Trace.node task.fully_qualified_name do
execute_task_without_benchmark task
end
end
class Node
attr_reader :name, :children, :total
def initialize(name)
@name = name
@children = []
@total = 0
end
def benchmark
@total = Benchmark.realtime { @result = yield }
@result
end
def time
total - nested
end
def nested
children.map(&:total).inject(:+).to_f
end
def create_child(name)
self.class.new(name).tap {|it| @children << it }
end
end
Node::TOPLEVEL = Node.new 'toplevel'
module Trace
extend self
@trace = [Node::TOPLEVEL]
def node(name, &block)
new_node = current_node.create_child name
with(new_node) { current_node.benchmark &block }
end
private
def current_node
@trace.last
end
def with(task)
@trace.push task
yield
ensure
@trace.pop
end
end
module Report
extend self
NUMBERS_MARGIN = 45
def print(node, level=0)
print_stats node, level unless level == 0
node.children.each {|it| print it, level+1 }
end
private
def print_stats(node, level)
puts intro(node,level) + fill_margin(node,level) + time(node)
end
def fill_margin(node, level)
'-' * margin_size(node, level)
end
def margin_size(node, level)
NUMBERS_MARGIN - intro(node, level).size
end
def intro(node, level)
"#{ident level}. #{node.name}"
end
def ident(level)
' ' * level + level.to_s
end
def time(node)
"-- #{format_time node.total} -- " +
"-- #{format_time node.nested} -- " +
"-- #{format_time node.time}"
end
def format_time(time)
'%5.1fs' % time
end
end
end
Capistrano::Configuration.send :include, Capistrano::Benchmark
at_exit { Capistrano::Benchmark.print }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment