Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get elapsed time in milliseconds in Ruby?

Tags:

ruby

If I have a Time object got from :

Time.now 

and later I instantiate another object with that same line, how can I see how many milliseconds have passed? The second object may be created that same minute, over the next minutes or even hours.

like image 737
Geo Avatar asked Sep 12 '09 12:09

Geo


People also ask

How do I get the current timestamp in Ruby?

The proper way is to do a Time. now. getutc. to_i to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.


1 Answers

As stated already, you can operate on Time objects as if they were numeric (or floating point) values. These operations result in second resolution which can easily be converted.

For example:

def time_diff_milli(start, finish)    (finish - start) * 1000.0 end  t1 = Time.now # arbitrary elapsed time t2 = Time.now  msecs = time_diff_milli t1, t2 

You will need to decide whether to truncate that or not.

like image 136
ezpz Avatar answered Oct 09 '22 21:10

ezpz