Last active
April 18, 2022 16:05
-
-
Save czogori/d498002f3278451b682316614a9345fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mix.install([ | |
{:benchee, "~> 1.0"} | |
]) | |
defmodule TestRecursion do | |
def sum([]), do: 0 | |
def sum([h|t]), do: h + sum(t) | |
end | |
defmodule TestTailRecursion do | |
def sum(list, acc \\ 0) | |
def sum([], acc), do: acc | |
def sum([h|t], acc), do: sum(t, acc + h) | |
end | |
list = Stream.repeatedly(fn -> :rand.uniform(50) end) |> Enum.take(10_000) | |
Benchee.run( | |
%{ | |
"sum recursion" => fn -> TestRecursion.sum(list) end, | |
"sum tail recursion" => fn -> TestTailRecursion.sum(list) end | |
}, | |
time: 10, | |
memory_time: 2 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment