Skip to content

Instantly share code, notes, and snippets.

@lguardiola
Created May 20, 2010 18:06
Show Gist options
  • Save lguardiola/407876 to your computer and use it in GitHub Desktop.
Save lguardiola/407876 to your computer and use it in GitHub Desktop.
multiproposed benchmark module
require 'benchmark'
require 'logger'
class Module
def alias_method_chain( target, feature )
alias_method "#{target}_without_#{feature}", target
alias_method target, "#{target}_with_#{feature}"
end
end unless Module.public_method_defined?(:alias_method_chain)
module Gasper
module Benchmark
class << self
def included(klass)
klass.extend ClassMethods
end
end
module ClassMethods
def benchmarked_dump(msg)
$stderr.puts(msg)
end
def benchmarked_method(*methods)
methods.each do |method|
class_eval %Q(
define_method("#{method.to_s}_with_benchmark".to_sym) do |*args, &block|
result = nil
runtime = ::Benchmark.realtime do
result = send(__method__.to_s.sub(/_with_/, '_without_').to_sym, *args, &block)
end
benchmarked_dump('benchmark for ' + __method__.to_s.sub(/_with_.*$/, '') + ': ' + runtime.to_s)
return result
end
)
alias_method_chain method, :benchmark
end
end
end
end
end
=begin
= Usage =
class String
include Gasper::Benchmark
benchmarked_method :scan, :upcase
benchmarked_method :gsub
end
"test".scan(/e/).first
scan: 4.291534423828125e-05
=> "e"
"test".upcase
scan: 3.14155342135614e-05
=> "TEST"
"test".gsub(/t/,'X')
gsub: 3.337860107421875e-05
=> "XesX"
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment