Ruby 如何查看哪个方法运行得更快

Ruby 如何查看哪个方法运行得更快,ruby,Ruby,我如何确定哪种方法运行得更快?阅读Ruby文档中的基准测试并实际实现它很困难。谢谢 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 因此,第一种变

我如何确定哪种方法运行得更快?阅读Ruby文档中的基准测试并实际实现它很困难。谢谢

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
    s = Benchmark.realtime do 
        list_of_integers.each do |x|
            count += 1 if x.between?(lower_bound, upper_bound) 
        end
    end
    puts "Method took #{"%.04f" % s} seconds to complete"
    count
end
Benchmark.realtime
将对其包含的块计时,并返回一个浮点数,该浮点数指示执行代码块所需的秒数(在浮点数精度和系统时钟精度范围内)


其他方法,如Benchmark.report和Benchmark.measure,将给出用户、系统和实际执行时间的细分,这有助于调试为什么一段代码比预期的慢。

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 

这使我们更容易看出结果是否重要。

该模块使用起来并不难。有什么你不明白的?检查一下。谢谢你们的回答。随着我对重构的深入,我想开始运行这些测试。
def count_between(list_of_integers, lower_bound, upper_bound)
    count = 0
    s = Benchmark.realtime do 
        list_of_integers.each do |x|
            count += 1 if x.between?(lower_bound, upper_bound) 
        end
    end
    puts "Method took #{"%.04f" % s} seconds to complete"
    count
end
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