当前位置 : 主页 > 编程语言 > ruby >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
如何确定哪种方法运行得更快?很难在 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)
如何确定哪种方法运行得更快?很难在 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
require 'benchmark'

def count_between_1(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_2(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

list_of_integers = (1..100_000).to_a
lower_bound = 5
upper_bound = 80_000

Benchmark.bm do |x|
  x.report do
    count_between_1(list_of_integers, lower_bound, upper_bound)
  end

  x.report do
    count_between_2(list_of_integers, lower_bound, upper_bound)
  end
end

结果如下:

user     system      total        real
 0.010000   0.000000   0.010000 (  0.008910)
 0.010000   0.000000   0.010000 (  0.018098)

所以第一个变种要快得多.

网友评论