Created
November 14, 2017 19:28
-
-
Save soulcutter/ba3bd3d58f0dcfd01abe1faeb1ed58f8 to your computer and use it in GitHub Desktop.
Instrumentation for methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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