Elapsed time -- tiny code snippet

H

Hal Fulton

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() }
 
F

Florian Groß

Hal said:
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.
 
T

Trans

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,170
Messages
2,570,924
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top