记忆技术

时间:2014-05-03 14:05:41

标签: ruby memoization

在尝试一些记忆技术时,我偶然发现这个基准测试结果与我的预期不符。似乎我犯了一些愚蠢的错误,有人看到我在做错了什么(基准测试给出了记忆和非记忆代码的相似结果)?

require 'benchmark'

# -----------------------------------------

class FactorialClass

  @@sequence = [1]

  def self.of( n )
    @@sequence[n] || n * of( n - 1 )
  end

end

# -----------------------------------------

def factorial_with_memoization
  sequence = [1]
  lambda = Proc.new do |n|
    sequence[n] || n * lambda.call( n - 1 )
  end
end
f = factorial_with_memoization()

# -----------------------------------------

def factorial n
 n == 0 ? 1 : n * factorial( n - 1 )
end

# -----------------------------------------



count = 1_000
n = 1000

without_memoization = Benchmark.measure do
  count.times do 
    factorial(n)
  end
end

with_memoization_lambda = Benchmark.measure do
  count.times do 
    f.call(n)
  end
end

with_memoization_class = Benchmark.measure do
  count.times do 
    FactorialClass.of(n)
  end
end


puts "Without memoization           : #{ without_memoization }"
puts "With memoization using lambda : #{ with_memoization_lambda }"
puts "With memoization using class  : #{ with_memoization_class }"

**结果是:**

Without memoization           :   1.210000   0.100000   1.310000 (  1.309675)
With memoization using lambda :   1.750000   0.100000   1.850000 (  1.858737)
With memoization using class  :   1.270000   0.090000   1.360000 (  1.358375)

1 个答案:

答案 0 :(得分:2)

您永远不会将任何记忆值分配给缓存。正如@xlembouras所说,你没有记住任何东西。

class FactorialClass
  @@sequence = [1]

  def self.of( n )
    # @@sequence[n] get evaluated to nil unless n is 0, always!
    @@sequence[n] || n * of( n - 1 )
  end
end

完成计算后,您需要手动将记忆值分配给缓存。

class FactorialClass
  @@sequence = [1]

  def self.of( n )
    @@sequence[n] = (@@sequence[n] || n * of( n - 1 ))
  end
end

但是,记忆真的适用于你的因子计算吗?否。

f(n) = n * f(n-1) = n * ((n-1) * f(n-2)) = ... = n * ((n-1) * (... * (3 * f(2))))

所有递归步骤计算新值的阶乘(从2到n),之前没有计算过。记忆不会在任何一步都被击中。