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
Ruby has a benchmarking tool in its standard library to help measure the performance of your code. It's most useful when comparing two implementations, to find out which is fastest. In this example, we're tasked with converting a Hash with string keys (like {"foo" => "bar"} to one with symbols (like {:foo => "bar"} ).
A benchmark is the standard by which performance is measured. The term benchmarking is used broadly in business, often to describe the process of measuring one thing against another to establish a standard acceptable value.
The simplest way:
require 'benchmark' def foo time = Benchmark.measure { code to test } puts time.real #or save it to logs end
Sample output:
2.2.3 :001 > foo 5.230000 0.020000 5.250000 ( 5.274806)
Values are: cpu time, system time, total and real elapsed time.
Source: ruby docs.
You could use the Time
object. (Time Docs)
For example,
start = Time.now # => 2022-02-07 13:55:06.82975 +0100 # code to time finish = Time.now # => 2022-02-07 13:55:09.163182 +0100 diff = finish - start # => 2.333432
diff
would be in seconds, as a floating point number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With