Measure and Benchmark Time for Ruby Methods

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

    Many of the answers suggest the use of Time.now. But it is worth being aware that Time.now can change. System clocks can drift and might get corrected by the system's administrator or via NTP. It is therefore possible for Time.now to jump forward or back and give your benchmarking inaccurate results.

    A better solution is to use the operating system's monotonic clock, which is always moving forward. Ruby 2.1 and above give access to this via:

    start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    # code to time
    finish = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    diff = finish - start # gets time is seconds as a float
    

    You can read more details here. Also you can see popular Ruby project, Sidekiq, made the switch to monotonic clock.

提交回复
热议问题