Skip to content

Instantly share code, notes, and snippets.

@jaturken
Created October 25, 2012 15:23
Show Gist options
  • Save jaturken/3953315 to your computer and use it in GitHub Desktop.
Save jaturken/3953315 to your computer and use it in GitHub Desktop.
Tail recursion benchmarking
def non_tail_recursive_factorial(n)
if n < 2
1
else
n * non_tail_recursive_factorial(n-1)
end
end
def tail_recursive_factorial(n, r = 1)
if n < 2
r
else
tail_recursive_factorial(n-1, n*r)
end
end
time_relations = []
cur_time = Time.now
(100..1000).each do |number|
cur_time = Time.now
tail_recursive_factorial number
tail_recursive_time = Time.now - cur_time
cur_time = Time.now
non_tail_recursive_factorial number
non_tail_recursive_time = Time.now - cur_time
time_relations << non_tail_recursive_time.to_f / tail_recursive_time.to_f
end
time_boost = time_relations.inject{ |sum, el| sum + el }.to_f / time_relations.size
p 'Tail call factorial spent time less at ' + time_boost.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment