Topic: Measuring execution time of a script (solved)

I'm not always on Linux, so I can't always use 'time'..
Is there a good Ruby way of measuring how long a program took to run?
Originally, I tried this:

a = DateTime.now
#
# Code here
#
b = DateTime.now
puts (b - a).to_s

But that gave me a rational number..

Is there a better/working solution?

Last edited by Trevoke (2008-10-14 10:41:23)

Re: Measuring execution time of a script (solved)

Figured it out..
Just have to do :

beginning = Time.now
# code block
puts "Time elapsed #{Time.now - beginning} seconds".

Re: Measuring execution time of a script (solved)

def time
  start = Time.now
  yield
  Time.now - start
end

time do
  # put code here ...
end

Re: Measuring execution time of a script (solved)

That's pretty neat -- thanks smile

Re: Measuring execution time of a script (solved)

Blocks is one of the most powerful features of Ruby, the sooner you learn how to use them the better!

Re: Measuring execution time of a script (solved)

Why my code does not work??

def time
  start = Time.now
  yield (Time.now - start).to_s
end

time do |t|
  1.upto(50000000) { |i| i*i  }
  puts t
end

Re: Measuring execution time of a script (solved)

simple:

start = Time.now
yield(Time.now - start).to_s.

You just called Time.now, hence why you are getting 0.0.

Here's a revision:

start = Time.now
1.upto(10000) { |i| i * i; puts "Time elapsed: #{Time.now - start} seconds"}

Re: Measuring execution time of a script (solved)

Why not just use the benchmarker and profiler scripts?

From AWDWR

depot> ruby script/performance/benchmarker \
> 'User.encrypted_password("secret", "salt")'
user system total real
#1 1.650000 0.030000 1.680000 ( 1.761335)

depot> ruby script/performance/profiler 'User.encrypted_password("secret", "salt")'
Loading Rails...
Using the standard Ruby profiler.
% cumulative self self total
time seconds seconds calls ms/call ms/call name
78.65 58.63 58.63 1 58630.00 74530.00 Integer#times
21.33 74.53 15.90 1000000 0.02 0.02 Math.sin
1.25 75.46 0.93 1 930.00 930.00 Profiler__.start_profile
0.01 75.47 0.01 12 0.83 0.83 Symbol#to_sym
. . .
0.00 75.48 0.00 1 0.00 0.00 Hash#update

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)