Measure and Benchmark Time for Ruby Methods

Phani picture Phani · Jul 10, 2012 · Viewed 58.5k times · Source

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

Answer

wquist picture wquist · Jul 10, 2012

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.