Forum: Ruby Adventures in Optimization.. When a Ruby primitive is the Hog.

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
John C. (Guest)
on 2008-12-02 02:10
(Received via mailing list)
So you've run your code with -rprofile or require 'profile'

And the answer was IO.each_line

Which is a bit like saying the answer to the Question of Life, the
Universe and Everything is "42".

a) You've used IO.each_line in many places.
b) There is nothing you can do to speed it up.

Enter Carter's Canny Primitive Profiler..


   CUNNING_MIN_CARE = 1 # Only care about stack frames that have been
                          # at least CUNNING_MIN_CARE times
   CUNNING_DEPTH    = 2   # Profile base on CUNNING_DEPTH number of
                          # stack frames of this calls that that
calls... that
                          # calls Array.each
                          # Make it -1 if you want the lot.

      $f.keys.find_all{|k| $f[k] >= CUNNING_MIN_CARE}.sort_by{|k|
         puts "\n\n#{k} >>>#{$f[k]}<<<"

class IO
    alias_method :orig_each_line, :each_line
    def each_line(&block)
       orig_each_line do |l|

          i+= 1
       $f[caller(1)[0..CUNNING_DEPTH].join("\n")] += i

On exit you can _see_ which invocation of each_line via which path was
the busiest!

Of course, sometimes we don't actually care about CPU time. The by
several orders of magnitude, the slowest operation in a modern PC is
pulling stuff of the disk.

So how about this variation on the Theme...
class IO
    alias_method :orig_read, :read
    def read(*arg)
       start =
       $f[caller(1)[0..CUNNING_DEPTH].join("\n")] += - start

I love Ruby :-)

John C.                             Phone : (64)(3) 358 6639
Tait Electronics                        Fax   : (64)(3) 359 4632
PO Box 1645 Christchurch                Email : 
New Zealand
This topic is locked and can not be replied to.