Skip to content

Instantly share code, notes, and snippets.

@michalmuskala
Created October 1, 2015 10:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michalmuskala/7feffb201219de0c6276 to your computer and use it in GitHub Desktop.
Save michalmuskala/7feffb201219de0c6276 to your computer and use it in GitHub Desktop.
defmodule MyBench do
use Benchfella
defmacro benchp(name, [do: block]) do
quote do
bench unquote(name) do
top = self
spawn fn ->
result = unquote(block)
send top, {:result, result}
end
receive do
{:result, result} -> result
end
end
end
end
end
defmodule MapBench do
use Benchfella
import MyBench
def map_cons([], _fun), do: []
def map_cons([head | tail], fun), do: [fun.(head) | map_cons(tail, fun)]
def map_recurse(list, fun, acc \\ [])
def map_recurse([], _fun, acc), do: :lists.reverse(acc)
def map_recurse([head | tail], fun, acc), do: map_recurse(tail, fun, [fun.(head) | acc])
def map_for(list, fun), do: for i <- list, do: fun.(i)
@list100 1..100 |> Enum.to_list
@list1000 1..1000 |> Enum.to_list
@list10000 1..10000 |> Enum.to_list
@list100000 1..100000 |> Enum.to_list
benchp "cons 100" do
@list100 |> map_cons(fn x -> x * 2 end)
end
benchp "cons 1000" do
@list1000 |> map_cons(fn x -> x * 2 end)
end
benchp "cons 10000" do
@list10000 |> map_cons(fn x -> x * 2 end)
end
benchp "cons 100000" do
@list100000 |> map_cons(fn x -> x * 2 end)
end
benchp "recurse 100" do
@list100 |> map_recurse(fn x -> x * 2 end)
end
benchp "recurse 1000" do
@list1000 |> map_recurse(fn x -> x * 2 end)
end
benchp "recurse 10000" do
@list10000 |> map_recurse(fn x -> x * 2 end)
end
benchp "recurse 100000" do
@list100000 |> map_recurse(fn x -> x * 2 end)
end
benchp "for 100" do
@list100 |> map_for(fn x -> x * 2 end)
end
benchp "for 1000" do
@list1000 |> map_for(fn x -> x * 2 end)
end
benchp "for 10000" do
@list10000 |> map_for(fn x -> x * 2 end)
end
benchp "for 100000" do
@list100000 |> map_for(fn x -> x * 2 end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment