Skip to content

Instantly share code, notes, and snippets.

@tmikeschu
Created June 24, 2018 15:51
Show Gist options
  • Save tmikeschu/e380a5b68e4af83e21fb2b81bd1e60cb to your computer and use it in GitHub Desktop.
Save tmikeschu/e380a5b68e4af83e21fb2b81bd1e60cb to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'json'
class Fib
def self.main
RubyVM::InstructionSequence.compile_option = {
tailcall_optimization: true,
trace_instruction: false
}
puts 'What number do you want to give Fib?'
new(gets.chomp.to_i).report
end
attr_reader :x
def initialize(x)
@x = x
end
def slow
return if x <= 0
[0, 1][x - 1] || Fib.new(x - 2).slow + Fib.new(x - 1).slow
end
def tail(y = x, a = 0, b = 1)
return if y == 0
[a, b][y - 1] || tail(y - 1, b, a + b)
end
def report(count = 100)
result = %i[tail slow].reduce({}) do |acc, el|
acc.merge(el => { average: average(el, count), result: send(el) })
end
puts JSON.pretty_generate(result)
end
private
def bm(&block)
Benchmark.realtime(&block)
end
def average(method, count)
(Array.new(count).map { bm { send(method) } }.reduce(:+) / count).round(5)
end
end
Fib.main if $PROGRAM_NAME == __FILE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment