Created
November 16, 2018 20:51
-
-
Save speeddragon/5c9944a2bd8b86cbbcbf77262e0c34c4 to your computer and use it in GitHub Desktop.
Benchmark Enum, Stream, etc
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
# | |
# O(2N) | |
# | |
t1 = :os.system_time(:millisecond) | |
v1 = 1..100_000 |> Enum.with_index() |> Enum.map(fn {x, y} -> x + y end) | |
IO.puts("t1: #{:os.system_time(:millisecond) - t1} ms") | |
# | |
# O(N) | |
# | |
t2 = :os.system_time(:millisecond) | |
{v2, _} = | |
1..100_000 |> Enum.reduce({[], 0}, fn x, {result, it} -> {result ++ [x + it], it + 1} end) | |
IO.puts("t2: #{:os.system_time(:millisecond) - t2} ms") | |
# | |
# Stream | |
# | |
t3 = :os.system_time(:millisecond) | |
v3 = 1..100_000 |> Stream.with_index() |> Stream.map(fn {x, y} -> x + y end) |> Enum.to_list() | |
IO.puts("t3: #{:os.system_time(:millisecond) - t3} ms ") | |
# Custom implement | |
defmodule Custom do | |
def iterate(value) do | |
iterate_internal(value, 0, []) | |
end | |
defp iterate_internal([], _, result) do | |
result | |
end | |
defp iterate_internal([head | tail], index, result) do | |
final_result = result ++ [head + index] | |
iterate_internal(tail, index + 1, final_result) | |
end | |
end | |
t4 = :os.system_time(:millisecond) | |
v4 = Custom.iterate(1..100_000 |> Enum.to_list()) | |
IO.puts("t4: #{:os.system_time(:millisecond) - t4} ms ") | |
# Just take 10 to not take to much time, looks like using reduce is too slow! | |
if v1 | |
|> Enum.take(10) | |
|> Enum.with_index() | |
|> Enum.reduce(true, fn {value, index}, result -> | |
result && | |
(value == Enum.at(v2, index) && value == Enum.at(v3, index) && value == Enum.at(v4, index)) | |
end) do | |
IO.puts("All values are the same.") | |
else | |
IO.puts("Wrong values.") | |
end | |
# Final Results | |
# | |
# t1: 34 ms | |
# t2: 27572 ms | |
# t3: 23 ms | |
# t4: 25156 ms | |
# All values are the same. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment