fork(1) download
  1. require 'benchmark'
  2.  
  3. class TriBonacci
  4. def initialize
  5. @memo = [1,1,2]
  6. end
  7. def f(n)
  8. return @memo[n] unless @memo[n] == nil
  9. @memo[n] = f(n-1) + f(n-2) + f(n-3)
  10. end
  11. def calc(n)
  12. last = @memo.length - 1
  13. return @memo[n] if n <= last
  14. (last + 1).upto(n-1) do |i|
  15. f(i)
  16. end
  17. f(n)
  18. end
  19. end
  20.  
  21. n = 6500
  22. Benchmark.bm do |x|
  23. x.report {TriBonacci.new.f(n)}
  24. x.report {TriBonacci.new.calc(n)}
  25. end
  26.  
  27.  
Success #stdin #stdout 0.07s 12056KB
stdin
Standard input is empty
stdout
                 user     system      total        real
             0.020000   0.000000   0.020000 (  0.028661)
             0.020000   0.000000   0.020000 (  0.026711)