Measure and Benchmark Time for Ruby Methods

后端 未结 6 1025
长情又很酷
长情又很酷 2021-01-30 06:04

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 meth

6条回答
  •  野的像风
    2021-01-30 06:36

    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
      end
    end
    

    This will output something like the following:

                            user     system      total        real
    Access 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.

提交回复
热议问题