Measure and Benchmark Time for Ruby Methods Measure and Benchmark Time for Ruby Methods ruby ruby

Measure and Benchmark Time for Ruby Methods


You could use the Time object. (Time Docs)

For example,

start = Time.now# code to timefinish = Time.nowdiff = finish - start

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

EDIT: end is reserved.


The simplest way:

require 'benchmark'def foo time = Benchmark.measure {  code to test } puts time.real #or save it to logsend

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.


Use Benchmark's Report

require 'benchmark' # Might be necessary.def foo  Benchmark.bm( 20 ) do |bm|  # The 20 is the width of the first column in the output.    bm.report( "Access Database:" ) do       # Code to access database.    end       bm.report( "Access Redis:" ) do      # Code to access redis.    end  endend

This will output something like the following:

                        user     system      total        realAccess Database:    0.020000   0.000000   0.020000 (  0.475375)Access Redis:       0.000000   0.000000   0.000000 (  0.000037)<------ 20 -------> # This is where the 20 comes in. NOTE: This is not shown in output.

More information can be found here.