Ruby-on-rails – Measure and Benchmark Time for Ruby Methods

benchmarkinginterpreterrubyruby-on-railstime

How can i measure the time taken by a method and the individual statements in that method in Ruby. If you see the below method i want to measure the total time taken by the method and the time taken for database access and redis access. I do not want to write Benchmark.measure before every statement. Does the ruby interpreter gives us any hooks for doing this ?

def foo
# code to access database
# code to access redis. 
end

Best Answer

You could use the Time object. (Time Docs)

For example,

start = Time.now
# code to time
finish = Time.now

diff = finish - start

diff would be in seconds, as a floating point number.

EDIT: end is reserved.