Created
June 5, 2024 22:24
-
-
Save mdepolli/c5cb274d9ce4028c75ab82a07c82fe42 to your computer and use it in GitHub Desktop.
This file contains hidden or 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]) | |
defmodule Test do | |
def benchmark() do | |
vector1 = Enum.map(1..1536, fn _ -> :rand.uniform() end) | |
vector2 = Enum.map(1..1536, fn _ -> :rand.uniform() end) | |
Benchee.run( | |
%{ | |
"dot_product_enum" => fn -> dot_product_enum(vector1, vector2) end, | |
"dot_product_recursion" => fn -> dot_product_recursion(vector1, vector2) end, | |
"dot_product_tco" => fn -> dot_product_tco(vector1, vector2) end | |
}, | |
time: 5, | |
memory_time: 2 | |
) | |
end | |
def dot_product_enum(vector1, vector2) do | |
vector1 | |
|> Enum.zip(vector2) | |
|> Enum.reduce(0, fn {x, y}, acc -> acc + x * y end) | |
end | |
def dot_product_recursion([], []), do: 0 | |
def dot_product_recursion([x | vector1], [y | vector2]) do | |
x * y + dot_product_recursion(vector1, vector2) | |
end | |
def dot_product_tco(vec1, vec2, acc \\ 0) | |
def dot_product_tco([], [], acc), do: acc | |
def dot_product_tco([x | vector1], [y | vector2], acc) do | |
dot_product_tco(vector1, vector2, x * y + acc) | |
end | |
end | |
Test.benchmark() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment