Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Instrumentation for methods
module Instrumenter
class Instrumentation < Module
def initialize(method, label)
@method = method
@label = label
define_method(method) do |*args|
start_time = Time.now
super(*args).tap do
end_time = Time.now
puts "#{label}: #{end_time - start_time}s"
end
end
end
def inspect
klass = self.class.name || self.class.inspect
"#<#{klass}: method=#{@method.inspect} label=#{@label.inspect}>"
end
end
module_function
def instrument_method(klass, method, label: "#{klass.name}##{method}")
klass.prepend(Instrumentation.new(method, label))
end
def instrument_class_method(klass, method, label: "#{klass.name}.#{method}")
instrument_method(klass.singleton_class, method, label: label)
end
end
__END__
## Example usage
class Foo
def foo
sleep 1
end
def self.bar
sleep 2
end
end
Instrumenter.instrument_method(Foo, :foo)
Instrumenter.instrument_class_method(Foo, :bar)
Foo.bar
# (STDOUT) Foo.bar: 2.000576s
# => 2
Foo.new.foo
# (STDOUT) Foo#foo: 1.005025s
# => 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.