Skip to content

Instantly share code, notes, and snippets.

@rjnienaber
Created December 17, 2012 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjnienaber/4317011 to your computer and use it in GitHub Desktop.
Save rjnienaber/4317011 to your computer and use it in GitHub Desktop.
require 'stopwatch'
class Dummy
extend MethodDecorators
+Stopwatch
def test
sleep(0.1)
end
+Stopwatch.new("custom name")
def test2
sleep(0.2)
end
+Stopwatch
def test_with_block(&blk)
blk.call
end
end
#Examples
Dummy.new.test #outputs 'Dummy.test, Elapsed...'
Dummy.new.test2 #outputs 'custom name, Elapsed...'
Dummy.new.test_with_block { sleep(0.3) } #outputs 'Dummy.test_with_block, Elapsed...'
Stopwatch.time("Block instrumentation") { sleep(0.4) } #outputs 'Block instrumentation, Elapsed...'
Stopwatch.time { sleep(0.5) } #outputs 'Elapsed...'
require 'method_decorators'
class Stopwatch < MethodDecorator
def initialize(name=nil)
@name = name
end
def call(original, this, *args, &blk)
time(original) { original.call(*args, &blk) }
end
def self.time(name=nil, &block)
Stopwatch.new(name).time { block.call }
end
def time(method=nil, &blk)
start = Time.now
begin
blk.call
ensure
if @name
message = "#{@name}, "
else
message = case method
when Method then "#{method.owner}.#{method.name}, "
when nil then ""
else "#{method}, "
end
end
puts "#{message}Elapsed: #{Time.now - start}s"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment