ruby – 如何查看哪种方法运行得更快
发布时间:2020-12-17 01:34:40 所属栏目:百科 来源:网络整理
导读:如何确定哪种方法运行得更快?很难在 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 counte
如何确定哪种方法运行得更快?很难在
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,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,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,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,upper_bound) end x.report do count_between_2(list_of_integers,upper_bound) end end 结果如下: user system total real 0.010000 0.000000 0.010000 ( 0.008910) 0.010000 0.000000 0.010000 ( 0.018098) 所以第一个变种要快得多. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |