Skip to content

Instantly share code, notes, and snippets.

@jrichter
Created January 4, 2011 02:26
Show Gist options
  • Save jrichter/764304 to your computer and use it in GitHub Desktop.
Save jrichter/764304 to your computer and use it in GitHub Desktop.
This is simply to test tracking the time of method calls
#---
# Excerpted from "Programming Ruby 1.9",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information.
#---
# I modified this code a little
module TraceCalls
@@time_hash = Hash.new
@@time_hash["total"] = 0
@@time_hash["total_calls"] = 0
@@time_hash["avg"] = 0
def self.included(klass)
klass.instance_methods(false).each do |existing_method|
wrap(klass, existing_method)
end
def klass.method_added(method) # note: nested definition
unless @trace_calls_internal
@trace_calls_internal = true
TraceCalls.wrap(self, method)
@trace_calls_internal = false
end
end
end
def self.wrap(klass, method)
klass.instance_eval do
method_object = instance_method(method)
define_method(method) do |*args, &block|
time = Time.now
puts "==> calling #{method} with #{args.inspect}"
result = method_object.bind(self).call(*args, &block)
puts "<== #{method} returned #{result.inspect}"
@@time_hash[method] = Time.now - time
@@time_hash["total_calls"] += 1
@@time_hash["total"] = @@time_hash["total"] + @@time_hash[method]
@@time_hash["avg"] = @@time_hash["total"] / @@time_hash["total_calls"]
puts "#{method}: #{@@time_hash[method]} seconds"
puts "Total: #{@@time_hash["total"]} seconds"
puts "Avg of #{@@time_hash["total_calls"]} method calls: #{@@time_hash["avg"]}"
result
end
end
end
end
class TimeTest
include TraceCalls
def add(a,b)
a + b
end
def subtract(a,b)
a - b
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment