From: Logan Capaldo Date: 2006-05-11T08:17:09+09:00 Subject: Re: Module#add_tracer On May 10, 2006, at 6:45 PM, Victor Shepelev wrote: > Hi all. > > Problem > ------- > Sometimes profiling of large library gives me results like: > > % cumulative self self total > time seconds seconds calls ms/call ms/call name > ... > 10.60 2.20 0.38 210 1.81 6.45 > Kernel.instance_eval > ... > > And I have a question "who had called Kernel#instance_eval so many > times?" > > Solution > -------- > class Module > def add_tracer(meth) > m_alias = case meth > when :[] : "old_idx" > when :+ : "old_plus" > when :- : "old_minus" > #and so on > else ; "old_#{meth}" > end > module_eval %Q{ > alias :#{m_alias} :#{meth} > def #{meth}(*arg, &block) > puts caller[0] + ": " + self.class.name + "##{meth} called" > #{m_alias}(*arg, &block) > end > } > end > end > > Usage > ----- > Kernel.add_tracer(:instance_eval) > call_my_long_routine() > > Which gives me desired information: > .... > D:/tmp/test.rb:11:in `call_my_long_routine': Object#instance_eval > called > .... > > Isn't it cool? :) > Seriously, I think my solution has many drawbacks, but it helps me. > Maybe it will help somebody else. > > Victor. > > -------------------------------------------------- Kernel#set_trace_func set_trace_func(proc) => proc set_trace_func(nil) => nil ------------------------------------------------------------------------ Establishes proc as the handler for tracing, or disables tracing if the parameter is nil. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc. class Test def test a = 1 b = 2 end end set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname } t = Test.new t.test line prog.rb:11 false c-call prog.rb:11 new Class c-call prog.rb:11 initialize Object c-return prog.rb:11 initialize Object c-return prog.rb:11 new Class line prog.rb:12 false call prog.rb:2 test Test line prog.rb:3 test Test line prog.rb:4 test Test return prog.rb:4 test Test