, 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(:+)
$timings
$timings will contain a runtime history of all methods containing the synchronization code.
source
share