What is the idiomatic way to measure time in Ruby?

This is pretty ugly:

t = Time.now
result = do_something
elapsed = Time.now - t

I tried this:

elapsed = time do
  result = do_something
end

def time
  t = Time.now
  yield
  Time.now - t
end

This is better. But the problem is that it resultgoes beyond the scope after the completion of the block.

So, is there a better way to make a timing? Or a good way to use result?

+4
source share
3 answers

The idiomatic way could be to use the standard library. :)

require 'benchmark'

result = nil
elapsed = Benchmark.realtime do 
  result = do_something
end
+4
source

You have the right idea here, but to avoid the problem with the scope, do the following:

result = nil
elapsed = time do
  result = do_something
end
+2
source

, time. , . , . - , :

require 'time'

t = Time.now
rv = my_method(*args)
et = t.Time.now - t

. , , , my_method my_method, , .

, , . - stop_at_zero, , , (.. StopIteration). :

arr.stop_at_zero.reduce(:+)

, stop_at_zero, .

class Array
  def stop_at_zero
    extime = Time.now
    Enumerator.new do |y|
      begin
        each do |n|
          sleep(0.5)
          return y if n.zero?
          y << n
        end
      ensure
        $timings << [__method__, Time.now - extime]
      end
    end
  end
end

I used block begin, ensure, endto make sure that $timings << [__method__, Time.now - extime]is done, when the method returns prematurely. sleep(0.5)Of course, just for illustrative purposes.

Give it a try.

$timings = []
arr = [1,7,0,3,4]
arr.stop_at_zero.reduce(:+)
  #=> 8 
$timings
  #=> [[:stop_at_zero, 1.505672]] 

$timings will contain a runtime history of all methods containing the synchronization code.

+2
source

Source: https://habr.com/ru/post/1655509/


All Articles