How to time an operation in milliseconds in Ruby?

Related searches

I'm wishing to figure out how many milliseconds a particular function uses. So I looked high and low, but could not find a way to get the time in Ruby with millisecond precision.

How do you do this? In most programming languages its just something like

start = now.milliseconds
myfunction()
end = now.milliseconds
time = end - start

You can use ruby's Time class. For example:

t1 = Time.now
# processing...
t2 = Time.now
delta = t2 - t1 # in seconds

Now, delta is a float object and you can get as fine grain a result as the class will provide.

How do I get elapsed time in milliseconds in Ruby?, As stated already, you can operate on Time objects as if they were numeric (or floating point) values. These operations result in second� If you want the time zone offset you can use the utc_offset method. The output for this method is in seconds, but you can divide by 3600 to get it in hours. Example: t = Time.now t.zone # "CET" t.utc_offset / 3600 # 1 You can also get the current time in UTC: Time.now.utc Ruby Time Formatting. Ruby formats Time objects in a specific way by default.

You can also use the built-in Benchmark.measure function:

require "benchmark"
puts(Benchmark.measure { sleep 0.5 })

Prints:

0.000000   0.000000   0.000000 (  0.501134)

Elapsed time with Ruby, the right way, When you want to calculate the elapsed time with Ruby, what do you usually do? starting = Time.now # time consuming operation ending = Time.now [It] gives the number of seconds and microseconds since the Epoch. Ruby ISO8601 time in milliseconds. GitHub Gist: instantly share code, notes, and snippets.

Using Time.now (which returns the wall-clock time) as base-lines has a couple of issues which can result in unexpected behavior. This is caused by the fact that the wallclock time is subject to changes like inserted leap-seconds or time slewing to adjust the local time to a reference time.

If there is e.g. a leap second inserted during measurement, it will be off by a second. Similarly, depending on local system conditions, you might have to deal with daylight-saving-times, quicker or slower running clocks, or the clock even jumping back in time, resulting in a negative duration, and many other issues.

A solution to this issue is to use a different time of clock: a monotonic clock. This type of clock has different properties than the wall clock. It increments monitonically, i.e. never goes back and increases at a constant rate. With that, it does not represent the wall-clock (i.e. the time you read from a clock on your wall) but a timestamp you can compare with a later timestamp to get a difference.

In Ruby, you can use such a timestamp with Process.clock_gettime(Process::CLOCK_MONOTONIC) like follows:

t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# => 63988.576809828

sleep 1.5 # do some work

t2 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
# => 63990.08359163

delta = t2 - t1
# => 1.5067818019961123
delta_in_milliseconds = delta * 1000
# => 1506.7818019961123

The Process.clock_gettime method returns a timestamp as a float with fractional seconds. The actual number returned has no defined meaning (that you should rely on). However, you can be sure that the next call will return a larger number and by comparing the values, you can get the real time difference.

These attributes make the method a prime candidate for measuring time differences without seeing your program fail in the least opportune times (e.g. at midnight at New Year's Eve when there is another leap-second inserted).

The Process::CLOCK_MONOTONIC constant used here is available on all modern Linux, BSD, and macOS systems as well as the Linux Subsystem for Windows. It is however not yet available for "raw" Windows systems. There, you can use the GetTickCount64 system call instead of Process.clock_gettime which also returns a timer value in millisecond granularity on Windows (>= Windows Vista, Windows Server 2008).

With Ruby, you can call this function like this:

require 'fiddle'

# Get a reference to the function once
GetTickCount64 = Fiddle::Function.new(
  Fiddle.dlopen('kernel32.dll')['GetTickCount64'],
  [],
  -Fiddle::TYPE_LONG_LONG # unsigned long long
)

timestamp = GetTickCount64.call / 1000.0
# => 63988.576809828

How to Use Ruby Time & Date Classes (With Examples), Learn how to work with Ruby time & date classes. How to convert strings into time objects; How to break down a time into components (day/hours/milliseconds …) How to use the You can use a method to get almost any format you need. As the documentation says, “The time options (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and minute is passed, then sec and usec is set to 0.”. To truncate a Time to the second, minute, hour, or day:

You should take a look at the benchmark module to perform benchmarks. However, as a quick and dirty timing method you can use something like this:

def time
  now = Time.now.to_f
  yield
  endd = Time.now.to_f
  endd - now
end

Note the use of Time.now.to_f, which unlike to_i, won't truncate to seconds.

Class: Time (Ruby 2.6.4), As stated already, you can operate on Time objects as if they were numeric (or floating point) values. These operations result in second� Hi How to convert UTC DateTime to Milliseconds or ticks in Ruby on rails,below attached sample code getting UTC DateTime date =DateTime.now.utc 2018-05-01 14:42:28 UTC I want that above DateTime to milliseconds

Use Time.now.to_f

How do I get elapsed time in milliseconds in Ruby?, The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038.

1 second has 1000 milliseconds Then the number of milliseconds in a year can be calculated in this way; Days multiply by hours multiply by minutes multiply by seconds multiply by milliseconds will give you the number of milliseconds in a year. 365 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds

@Taimoor Changaiz its not correct it gives time relative to Time.at(0). – Rahul Tapali Feb 6 '13 at 3:44 @checkit So whats the hack to get current time with at method, I think we could manipulate given miliseconds with relative?

milliseconds = (time. to_i * 1000) + (time. usec / 1000.0). round IMHO, it is generally preferable to avoid time travel by truncating to the beginning of the "present" millisecond rather than possibly rounding to the beginning of the "future" millisecond. #4 [ruby-core:77997] Updated by akr (Akira Tanaka) over 3 years ago

Comments
  • This is the easy solution, but better is the answer with Process.clock_gettime. See blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way
  • I like the idea of using a built in library, but what are the first three numbers (the 0.000000)? Update: Looked it up in the docs and it's user CPU time, system CPU time, and sum of those two.
  • Yes. They are labeled if you use Benchmark.bm. It is useful to see where the time is spent sometimes. Here you can see that the block is just idling (0 total, 0.5 real)
  • Or there's a Benchmark.realtime which returns a single understandable float :)
  • This is the only answer that should be acceptable, let alone accepted.
  • Maybe worth adding some details about OS support: SUSv3 to 4, Linux 2.5.63, FreeBSD 3.0, NetBSD 2.0, OpenBSD 3.4, macOS 10.12
  • The original question and answer were both provided before this solution was available. Why should this be the only "acceptable" answer?
  • Casting times to floats here is unnecessary.
  • also, typo in "endd"
  • @nightpool It's spelled that way because end is a keyword.
  • then do like end_time or something, don't just misspell words, that's sloppy as hell
  • or hitimes gem which may have higher granularity on windows than absolute_time ...
  • .to_i gives an integer and would truncate the milliseconds. This would work if you just changed it to .to_f
  • Yeah, as Ryan says; apologies for the downvote, but this actually had one upvote and I felt compelled to counteract it. Multiplying an integer time difference in seconds by 1000 to get milliseconds? C'mon now, MARC.RS, surely you were just trolling us! :-)
  • Nope, just trying my best