如何确定哪个方法运行得更快?很难阅读 Ruby 文档中的 Benchmark 并实际实现它。谢谢
def count_between(list_of_integers, lower_bound, upper_bound)
count = 0
list_of_integers.each do |x|
(x >= lower_bound && x <= upper_bound) ? count += 1 : next
end
count
end
或
def count_between(list_of_integers, lower_bound, upper_bound)
count = 0
list_of_integers.each do |x|
count += 1 if x.between?(lower_bound, upper_bound)
end
count
end
最佳答案
基准测试的问题在于,对于执行速度非常快的东西,您需要多次运行测试才能对结果有信心。 Benchmark 对此没有任何帮助 - 您最终会在 report
block 中出现循环并修改重复的执行计数。
benchmark-ips gem 为您做了一些。基本用法与 stdlib 版本几乎相同:
require 'benchmark/ips'
#define your methods and test data here.
Benchmark.ips do |x|
x.report 'count between 1' do
count_between_1(list_of_integers, lower_bound, upper_bound)
end
x.report 'count between 2' do
count_between_2(list_of_integers, lower_bound, upper_bound)
end
end
产生类似的输出
count between 1 143.377 (± 4.9%) i/s - 728.000
count between 2 64.489 (± 4.7%) i/s - 324.000
这使得查看结果是否显着变得更容易一些。
关于ruby - 如何查看哪种方法运行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28964133/