From: "Jesús Gabriel y Galán" Date: 2008-04-16T19:24:56+09:00 Subject: Re: Calculating elapsed time On Wed, Apr 16, 2008 at 11:56 AM, Clement Ow wrote: > I have a program where i put the time at the beginning: > puts $t1=Time.now > > and then after running some commands, i put the time again: > puts $t2=Time.now > > and then have a method to calculate the time elapsed: > def calTime > starttime_sec= $t1.strftime("%S").to_i > starttime_min= $t1.strftime("%M").to_i > endtime_sec= $t2.strftime("%S").to_i > endtime_min= $t2.strftime("%M").to_i > diff_sec= endtime_sec - starttime_sec > diff_sec1= diff_sec.to_s > diff_min= endtime_min - starttime_min > diff_min1= diff_min.to_s > puts "\nElapsed time:\n "+ "Min-> " +diff_min1 + " Sec-> "+ diff_sec1 > > However, the calculation has limitations because if the start time is > say, 4:50 and the end time is 5:10, it will return an errorneous value > like -49 for the Min value, which is obviously not what we want.. > > Any alternative method or any corrections to the method are welcome. ;) Alternative: irb(main):001:0> start = Time.now => Wed Apr 16 12:06:23 +0200 2008 irb(main):003:0> finish = Time.now => Wed Apr 16 12:07:24 +0200 2008 irb(main):005:0> elapsed = (finish - start).to_i => 65 irb(main):012:0> mins = elapsed / 60 => 1 irb(main):013:0> secs = elapsed % 60 => 5 Jesus.