Ruby 的 range step 方法导致执行很慢? [英] Ruby's range step method causes very slow execution?

查看:26
本文介绍了Ruby 的 range step 方法导致执行很慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

date_counter = Time.mktime(2011,01,01,00,00,00,"+05:00")
@weeks = Array.new
(date_counter..Time.now).step(1.week) do |week|
   logger.debug "WEEK: " + week.inspect
   @weeks << week
end

从技术上讲,代码有效,输出:

Technically, the code works, outputting:

Sat Jan 01 00:00:00 -0500 2011
Sat Jan 08 00:00:00 -0500 2011
Sat Jan 15 00:00:00 -0500 2011
etc.

但是执行时间完全是垃圾!每周计算大约需要四秒钟.

But the execution time is complete rubbish! It takes approximately four seconds to compute each week.

我在这段代码中是否遗漏了一些奇怪的低效率?这似乎很简单.

Is there some grotesque inefficiency that I'm missing in this code? It seems straight-forward enough.

我正在运行 Ruby 1.8.7 和 Rails 3.0.3.

I'm running Ruby 1.8.7 with Rails 3.0.3.

推荐答案

假设 MRI 和 Rubinius 使用类似的方法来生成范围,那么使用所有无关检查和一些 Fixnum 优化等的基本算法是:

Assuming MRI and Rubinius use similar methods to generate the range the basic algorithm used with all the extraneous checks and a few Fixnum optimisations etc. removed is:

class Range
  def each(&block)
    current = @first
    while current < @last
      yield current
      current = current.succ
    end
  end

  def step(step_size, &block)
    counter = 0
    each do |o|
      yield o if counter % step_size = 0
      counter += 1
    end
  end
end

(参见 Rubinius 源代码)

对于 Time 对象,#succ 返回一秒后的时间.因此,即使您只要求每周一次,它也必须在两次之间的每一秒内逐步完成.

For a Time object #succ returns the time one second later. So even though you are asking it for just each week it has to step through every second between the two times anyway.

构建一系列 Fixnum,因为它们具有优化的 Range#step 实现.比如:

Build a range of Fixnum's since they have an optimised Range#step implementation. Something like:

date_counter = Time.mktime(2011,01,01,00,00,00,"+05:00")
@weeks = Array.new

(date_counter.to_i..Time.now.to_i).step(1.week).map do |time|
  Time.at(time)
end.each do |week|
  logger.debug "WEEK: " + week.inspect
  @weeks << week
end

这篇关于Ruby 的 range step 方法导致执行很慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆