Skip to content

Instantly share code, notes, and snippets.

@artemrizhov
Created December 16, 2016 00:44
Show Gist options
  • Save artemrizhov/fc146f7ab390f7a807be833099e5cb83 to your computer and use it in GitHub Desktop.
Save artemrizhov/fc146f7ab390f7a807be833099e5cb83 to your computer and use it in GitHub Desktop.
Compare Enum.map|>Enum.sum against Enum.count in Elixir (map won)
defmodule Test do
@moduledoc """
Tested with:
Erlang/OTP 19 [erts-8.1] [source-e7be63d] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Elixir 1.3.4
Output:
len = 10
map: 0.6671 µs
count: 2.5472 µs
len = 100
map: 5.521 µs
count: 8.914 µs
len = 1000
map: 59.0 µs
count: 73.12 µs
len = 10000
map: 642.5 µs
count: 734.6 µs
"""
def run do
iterations = 100000
for len <- [10, 100, 1000, 10000] do
%{t_map: t_map, t_count: t_count} = test(iterations, len)
IO.puts "\nlen = #{len}"
IO.puts "map: #{t_map} µs"
IO.puts "count: #{t_count} µs"
end
end
def test(iterations, len) do
repeat = div(iterations, len)
elements = create_list(len)
%{
t_map: test_map(elements, repeat),
t_count: test_count(elements, repeat)
}
end
def create_list(len) do
1..len |> Enum.map(fn(_) -> :rand.uniform end)
end
def test_map(elements, repeat) do
timer repeat, fn ->
elements |> Enum.map(&(if check(&1), do: 1, else: 0)) |> Enum.sum
end
end
def test_count(elements, repeat) do
timer repeat, fn ->
elements |> Enum.count(&check/1)
end
end
def check(element) do
element < 0.5
end
def timer(repeat, func) do
{t, _} = :timer.tc fn ->
for _ <- 1..repeat do
func.()
end
end
t / repeat
end
end
Test.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment