Ruby 方法的度量和基准时间

我如何在 Ruby 中度量一个方法所花费的时间以及该方法中的各个语句。如果你看到下面的方法,我想测量的总时间采取的方法和时间采取的数据库访问和重新访问。我不想在每个陈述之前都写 Benchmark.test。Ruby 解释器给我们提供了这样做的工具吗?

def foo
# code to access database
# code to access redis.
end
81190 次浏览

您可以使用 Time对象

比如说,

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将以秒为单位,作为一个浮点数。

本着 Wquist 的回答的精神,但是更简单一点,你也可以像下面这样做:

start = Time.now
# code to time
Time.now - start

The simplest way:

require 'benchmark'


def foo
time = Benchmark.measure {
code to test
}
puts time.real #or save it to logs
end

输出样本:

2.2.3 :001 > foo
5.230000   0.020000   5.250000 (  5.274806)

值是: CPU 时间、系统时间、总和实际运行时间。

资料来源: 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
end
end

这将输出如下内容:

                        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 给你.

第二个想法是,使用 Ruby 代码块参数定义 measure()函数可以帮助简化时间度量代码:

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

许多答案建议使用 Time.now。但是值得注意的是 Time.now是可以改变的。系统时钟可能会漂移,可能会由系统管理员或通过 NTP 进行修正。因此 Time.now 可以向前或向后跳转,并给出不准确的基准测试结果。

一个更好的解决方案是使用操作系统的单调时钟,它总是在前进。Ruby 2.1及以上版本可以通过以下方式进行访问:

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 给你. Also you can see popular Ruby project, Sidekiq, made the switch to 单调时钟单调时钟.