Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure and Benchmark Time for Ruby Methods

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 
like image 825
Phani Avatar asked Jul 10 '12 04:07

Phani


People also ask

What is benchmark in Ruby?

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"} ).

What is benchmark measure?

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.


2 Answers

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.

like image 106
Łukasz Ostrowski Avatar answered Sep 21 '22 07:09

Łukasz Ostrowski


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.

like image 37
wquist Avatar answered Sep 19 '22 07:09

wquist