ruby - 如何查看哪种方法运行得更快

标签 ruby

如何确定哪个方法运行得更快?很难阅读 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/

相关文章:

java - Ruby 相当于 64 位的 Calendar.getInstance().getTimeInMillis()

ruby-on-rails - 回应?当 self 可以调用该方法时返回 false,并且 super 似乎忽略对输入的更改

ruby-on-rails - Ruby on Rails : How to iterate whether the user already commented on the post

ruby - 在 Windows 中右键单击并选择 Ruby 的上下文菜单选项

ruby-on-rails - Rails bundle - 糟糕的解释器

ruby-on-rails - 如何为产生可迭代的函数添加默认错误处理?

ruby - 与嵌套类共享作用域

ruby-on-rails - 查找两个条件都为真的所有记录

ruby-on-rails - ruby rails : redirect unauthenticated user to root instead of the sign in page

ruby - Rspec 加载时间太长