Ruby中,如何比较不同方法的执行效率?

更新于
2026-10-09 19:21:29
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计281个文字,预计阅读时间需要2分钟。

Ruby中,如何比较不同方法的执行效率?

要确定哪种方法运行得更快,可以比较几种不同的方法来实现`count_between`函数。以下是一个Ruby示例,使用内置的`select`方法,它通常比手动迭代数组更快:

rubydef count_between(list_of_integers, lower_bound, upper_bound) count=list_of_integers.count { |x| lower_bound <=x && x <=upper_bound }end

如何确定哪种方法运行得更快?很难在 Ruby文档中阅读Benchmark并实际实现它.谢谢

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 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)

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

本文共计281个文字,预计阅读时间需要2分钟。

Ruby中,如何比较不同方法的执行效率?

要确定哪种方法运行得更快,可以比较几种不同的方法来实现`count_between`函数。以下是一个Ruby示例,使用内置的`select`方法,它通常比手动迭代数组更快:

rubydef count_between(list_of_integers, lower_bound, upper_bound) count=list_of_integers.count { |x| lower_bound <=x && x <=upper_bound }end

如何确定哪种方法运行得更快?很难在 Ruby文档中阅读Benchmark并实际实现它.谢谢

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 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)

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