Calculating elapsed time

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. :wink:

2008/4/16, Clement Ow [email protected]:

Any alternative method or any corrections to the method are welcome. :wink:

require ‘benchmark’

time = Benchmark.realtime {
do_all_stuff
}

puts “Elapsed time: #{time}”

:wink:

On Wed, Apr 16, 2008 at 11:56 AM, Clement Ow
[email protected] wrote:

endtime_sec= $t2.strftime(“%S”).to_i

Any alternative method or any corrections to the method are welcome. :wink:

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.

On Apr 16, 2008, at 6:24 AM, Jesús Gabriel y Galán wrote:

starttime_sec= $t1.strftime(“%S”).to_i
say, 4:50 and the end time is 5:10, it will return an errorneous
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.

or:
irb> start = Time.now
=> Wed Apr 16 10:41:03 -0400 2008
irb> finish = Time.now
=> Wed Apr 16 10:45:53 -0400 2008
irb> elapsed = finish.to_f - start.to_f # note to_f to keep
fractional seconds
=> 289.695813894272
irb> mins, secs = elapsed.divmod 60.0
=> [4, 49.6958138942719]
irb> puts(“%3d:%04.2f”%[mins.to_i, secs])
4:49.70
=> nil

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Thanks guys of the prompt reply! However, i’ll need help the
explanations though… Really appreciate that :wink:

Jesús Gabriel y Galán wrote:

On Wed, Apr 16, 2008 at 4:47 PM, Rob B.
[email protected] wrote:

or:
irb> start = Time.now
=> Wed Apr 16 10:41:03 -0400 2008
irb> finish = Time.now
=> Wed Apr 16 10:45:53 -0400 2008
irb> elapsed = finish.to_f - start.to_f # note to_f to keep fractional
seconds

Yep, I assumed he wanted to stop at the seconds level.

=> 289.695813894272
irb> mins, secs = elapsed.divmod 60.0
=> [4, 49.6958138942719]
irb> puts(“%3d:%04.2f”%[mins.to_i, secs])
how this line work? “%3d” and %04.2f" means selecting min and secs
respectively?
4:49.70
=> nil

I always forget about divmod, it’s a cool little method :slight_smile:

Jesus.

On Wed, Apr 16, 2008 at 4:47 PM, Rob B.
[email protected] wrote:

or:
irb> start = Time.now
=> Wed Apr 16 10:41:03 -0400 2008
irb> finish = Time.now
=> Wed Apr 16 10:45:53 -0400 2008
irb> elapsed = finish.to_f - start.to_f # note to_f to keep fractional
seconds

Yep, I assumed he wanted to stop at the seconds level.

=> 289.695813894272
irb> mins, secs = elapsed.divmod 60.0
=> [4, 49.6958138942719]
irb> puts(“%3d:%04.2f”%[mins.to_i, secs])
4:49.70
=> nil

I always forget about divmod, it’s a cool little method :slight_smile:

Jesus.

Hi,

Ruby substitutes the elements in the array for the percent signs in
the string. The “3d” and “04.2f” tell Ruby how to format those
numbers:

“The number is: %.2f” % 1.23456
=> “The number is: 1.23”

The documentation for sprintf has more info:
daniel@daniel-desktop:~/lightconsole$ ri sprintf
--------------------------------------------------------- Kernel#sprintf
format(format_string [, arguments…] ) => string
sprintf(format_string [, arguments…] ) => string

 Returns the string resulting from applying format_string to any
 additional arguments. Within the format string, any characters
 other than format sequences are copied to the result. A format
 sequence consists of a percent sign, followed by optional flags,
 width, and precision indicators, then terminated with a field type
 character. The field type controls how the corresponding sprintf
 argument is to be interpreted, while the flags modify that
 interpretation. The field type characters are listed in the table
 at the end of this section. The flag characters are:

   Flag     | Applies to   | Meaning
   ---------+--------------+-----------------------------------------
   space    | bdeEfgGiouxX | Leave a space at the start of
            |              | positive numbers.
   ---------+--------------+-----------------------------------------
   (digit)$ | all          | Specifies the absolute argument number
            |              | for this field. Absolute and relative
            |              | argument numbers cannot be mixed in a
            |              | sprintf string.
   ---------+--------------+-----------------------------------------
    #       | beEfgGoxX    | Use an alternative format. For the
            |              | conversions `o', `x', `X', and `b',
            |              | prefix the result with ``0'', ``0x'', 

0X'', | | and0b’’, respectively. For e', | |E’, f',g’, and ‘G’, force a decimal
| | point to be added, even if no digits
follow.
| | For `g’ and ‘G’, do not remove trailing
zeros.
---------±-------------±----------------------------------------
+ | bdeEfgGiouxX | Add a leading plus sign to positive
numbers.
---------±-------------±----------------------------------------
- | all | Left-justify the result of this
conversion.
---------±-------------±----------------------------------------
0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
---------±-------------±----------------------------------------
* | all | Use the next argument as the field
width.
| | If negative, left-justify the result.
If the
| | asterisk is followed by a number and a
dollar
| | sign, use the indicated argument as the
width.

 The field width is an optional integer, followed optionally by a
 period and a precision. The width specifies the minimum number of
 characters that will be written to the result for this field. For
 numeric fields, the precision controls the number of decimal
 places displayed. For string fields, the precision determines the
 maximum number of characters to be copied from the string. (Thus,
 the format sequence %10.10s will always contribute exactly ten
 characters to the result.)

 The field types are:

     Field |  Conversion
     ------+--------------------------------------------------------------
       b   | Convert argument as a binary number.
       c   | Argument is the numeric code for a single character.
       d   | Convert argument as a decimal number.
       E   | Equivalent to `e', but uses an uppercase E to indicate
           | the exponent.
       e   | Convert floating point argument into exponential 

notation
| with one digit before the decimal point. The precision
| determines the number of fractional digits (defaulting
to six).
f | Convert floating point argument as [-]ddd.ddd,
| where the precision determines the number of digits
after
| the decimal point.
G | Equivalent to g', but use an uppercaseE’ in exponent
form.
g | Convert a floating point number using exponential form
| if the exponent is less than -4 or greater than or
| equal to the precision, or in d.dddd form otherwise.
i | Identical to `d’.
o | Convert argument as an octal number.
p | The valuing of argument.inspect.
s | Argument is a string to be substituted. If the format
| sequence contains a precision, at most that many
characters
| will be copied.
u | Treat argument as an unsigned decimal number. Negative
integers
| are displayed as a 32 bit two’s complement plus one for
the
| underlying architecture; that is, 2 ** 32 + n.
However, since
| Ruby has no inherent limit on bits used to represent
the
| integer, this value is preceded by two dots (…) in
order to
| indicate a infinite number of leading sign bits.
X | Convert argument as a hexadecimal number using
uppercase
| letters. Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'FF’s.
x | Convert argument as a hexadecimal number.
| Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'ff’s.

 Examples:

    sprintf("%d %04x", 123, 123)               #=> "123 007b"
    sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
    sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 

hello"
sprintf("%1$*2$s %2$d", “hello”, -8) #=> “hello -8”
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> “+1.23:
1.23:1.23”
sprintf("%u", -123) #=> “…4294967173”

Dan

On Wed, Apr 16, 2008 at 9:38 PM, Clement Ow

That’s some information, thanks, dan!