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
The simplest way:
Sample output:
Values are: cpu time, system time, total and real elapsed time.
Source: ruby docs.
Use
Benchmark
's ReportThis will output something like the following:
More information can be found here.
Look into the
ruby-prof
package, it should have what you need. It will create huge call stacks with timings.http://ruby-prof.rubyforge.org/
It might be too granular, in which case just wrapping bigger sections in
Benchmark.measure
might be a good way to go.Many of the answers suggest the use of
Time.now
. But it is worth being aware thatTime.now
can change. System clocks can drift and might get corrected by the system's administrator or via NTP. It is therefore possible for Time.now to jump forward or back and give your benchmarking inaccurate results.A better solution is to use the operating system's monotonic clock, which is always moving forward. Ruby 2.1 and above give access to this via:
You can read more details here. Also you can see popular Ruby project, Sidekiq, made the switch to monotonic clock.
A second thought, define the measure() function with Ruby code block argument can help simplify the time measure code:
You could use the
Time
object. (Time Docs)For example,
diff
would be in seconds, as a floating point number.EDIT:
end
is reserved.