84

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
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Earlz
  • 62,085
  • 98
  • 303
  • 499

10 Answers10

95

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.

Nikita
  • 6,019
  • 8
  • 45
  • 54
ezpz
  • 11,767
  • 6
  • 38
  • 39
  • 2
    This is the easy solution, but better is the answer with Process.clock_gettime. See https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/ – Guy C Oct 18 '18 at 21:31
  • And even better is the answer with Benchmark.measure. Its implementation uses an monotonic clock. – Jonatan Lindén Nov 04 '21 at 10:13
64

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)
Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74
  • 1
    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](http://ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html) and it's user CPU time, system CPU time, and sum of those two. – lyonsinbeta Sep 05 '12 at 01:37
  • 1
    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) – Simon Perepelitsa Sep 05 '12 at 04:41
  • 17
    Or there's a `Benchmark.realtime` which returns a single understandable float :) – Sergio Tulentsev Oct 24 '12 at 09:52
38

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
Holger Just
  • 52,918
  • 14
  • 115
  • 123
  • 3
    This is the only answer that should be acceptable, let alone accepted. – Rob Kinyon Sep 12 '18 at 18:59
  • 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 – Guy C Oct 18 '18 at 21:32
  • The original question and answer were both provided before this solution was available. Why should this be the only "acceptable" answer? – CitizenX Jan 16 '19 at 21:45
14

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
2

Also we can create simple function to log any block of code:

def log_time
  start_at = Time.now

  yield if block_given?

  execution_time = (Time.now - start_at).round(2)
  puts "Execution time: #{execution_time}s"
end

log_time { sleep(2.545) } # Execution time: 2.55s
Slava Zharkov
  • 237
  • 3
  • 7
1

The absolute_time gem is a drop-in replacement for Benchmark, but uses native instructions to be far more accurate.

1

Use Time.now.to_f

sutch
  • 1,225
  • 1
  • 13
  • 28
0

The use of Time.now.to_i return the second passed from 1970/01/01. Knowing this you can do

date1 = Time.now.to_f
date2 = Time.now.to_f
diff = date2 - date1

With this you will have difference in second magnitude. If you want it in milliseconds, just add to the code

diff = diff * 1000
MARC.RS
  • 1,108
  • 1
  • 11
  • 15
  • 2
    ```.to_i``` gives an integer and would truncate the milliseconds. This would work if you just changed it to ```.to_f``` – Ryan Taylor May 06 '14 at 00:39
  • 1
    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! :-) – Andrew Hodgkinson Mar 25 '15 at 23:49
  • Nope, just trying my best – MARC.RS Jun 01 '15 at 11:21
0

If you use

date = Time.now.to_i

You're obtaining time in seconds, that is far from accurate, specially if you are timing little chunks of code.

user987339
  • 10,519
  • 8
  • 40
  • 45
0

I've a gem which can profile your ruby method (instance or class) - https://github.com/igorkasyanchuk/benchmark_methods.

No more code like this:

t = Time.now
user.calculate_report
puts Time.now - t

Now you can do:

benchmark :calculate_report # in class

And just call your method

user.calculate_report
Igor Kasyanchuk
  • 766
  • 6
  • 12