Measure and Benchmark Time for Ruby Methods

后端 未结 6 1026
长情又很酷
长情又很酷 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:31

    A second thought, define the measure() function with Ruby code block argument can help simplify the time measure code:

    def measure(&block)
      start = Time.now
      block.call
      Time.now - start
    end
    
    # t1 and t2 is the executing time for the code blocks.
    t1 = measure { sleep(1) }
    
    t2 = measure do
      sleep(2)
    end
    

提交回复
热议问题