How to calculate the difference between two different hours in milliseconds?

Asked

Viewed 1,134 times

1

How to calculate in milliseconds the time of an action in ruby?

I’m doing it this way:

start_time = Time.now
I run a certain code that takes a few milliseconds
end_time = (Time.now - start_time)

And as a result I get for example: 0.048813

The question is: This value I got is in milliseconds (ms) or is in seconds?

How do I check it with fewer decimal places, like 48.81 ms ?

1 answer

1


According to the documentation, the substation between two times returns a number of seconds. So you can get the value in milliseconds like this:

delta_time = (Time.now - start_time) * 1000

To display with only two decimal places you can use the sprintf. Thus:

puts "%.2f" % delta_time
  • Perfect. It worked fine. I had seen the documentation but didn’t understand this form of rounding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.