Search code examples
rubycodeblocksproc

Why do these two methods give me two different times?


Both methods calculate the time it takes ruby to call and run a code block. I don't see any reason why these two methods should return different results.

methodone gives me: 1.000135157

methodtwo gives me: 1.000108267

I'm a noob, am I even doing this right? please let me know.

def methodone(a)
  start = Time.now 
  a.call
  result = Time.now - start
end

def methodtwo(a)
  start_time = Time.now
  a.call
  end_time = Time.now
  result = end_time - start_time
end 

a = Proc.new do {}
end

p methodone(a)
p methodtwo(a)

Solution

  • You shouldn't expect them to be exactly the same. There will always be something going on outside of the Ruby process that will impact performance. You should consider a margin of error of, say, 0.1%

    def time(&block)
      t = Time.now.to_f
      yield 
      t2 = Time.now.to_f 
      puts t2 - t 
    end
    
    50.times do 
      time do 
        Proc.new { }
      end
    end