Elapsed time -- tiny code snippet

Here's a poor man's profiler -- only good for finding the
time in seconds it took to execute a code block. (I used
this today in a context where I was doing several operations
that invoked external programs and such.)

I put it inside Time just for convenience.

Cheers,
Hal

   class Time
     def self.elapse
       raise "Need block" unless block_given?
       t0 = Time.now
       yield
       Time.now - t0
     end
   end

   secs = Time.elapse { do_something() }

Hal Fulton wrote:

Here's a poor man's profiler -- only good for finding the
time in seconds it took to execute a code block. (I used
this today in a context where I was doing several operations
that invoked external programs and such.)

I put it inside Time just for convenience.

  class Time
    def self.elapse
      raise "Need block" unless block_given?
      t0 = Time.now
      yield
      Time.now - t0
    end
  end

  secs = Time.elapse { do_something() }

I'd suggest converting the times to floats (via .to_f) before subtracting -- it ought to be quite a bit more precise that way.

Tried it with and without floats, and yes float give more precision.
But strangely this happens either way:

  Time.elapse { sleep 1 } #=> 0.999188899993896

Not 1 or more? Odd.

T.

Tried it with and without floats, and yes float give more precision.
But strangely this happens either way:

  Time.elapse { sleep 1 } #=> 0.999188899993896

Not 1 or more? Odd.

You may find this
http://docs.sun.com/source/806-3568/ncg_goldberg.html interesting
reading.

···

On 4/13/05, Trans <transfire@gmail.com> wrote:

T.

--
Into RFID? www.rfidnewsupdate.com Simple, fast, news.