How to time an operation in milliseconds in Ruby?

2020-05-15 07:57发布

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

标签: ruby timer
10条回答
兄弟一词,经得起流年.
2楼-- · 2020-05-15 08:19

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.

查看更多
倾城 Initia
3楼-- · 2020-05-15 08:20

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
查看更多
forever°为你锁心
4楼-- · 2020-05-15 08:26

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)
查看更多
疯言疯语
5楼-- · 2020-05-15 08:26

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.

查看更多
地球回转人心会变
6楼-- · 2020-05-15 08:29

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

查看更多
Deceive 欺骗
7楼-- · 2020-05-15 08:34

Use Time.now.to_f

查看更多
登录 后发表回答