defmodule CondTest do
def odds_and_evens_acc(l) do
odds_and_evens_acc(l,[],[])
end
def odds_and_evens_acc([h|t], odds, evens) do
cond do
rem(h,2) == 0 -> odds_and_evens_acc(t, odds, [h|evens])
rem(h,2) == 1 -> odds_and_evens_acc(t, [h|odds], evens)
end
end
def odds_and_evens_acc([], odds, evens) do
{odds, evens}
end
def benchmark(n \\ 10000) do
coll = Enum.into(1..1000,[])
:erlang.statistics(:runtime)
:erlang.statistics(:wall_clock)
Enum.each(1..n, fn(_i)-> odds_and_evens_acc(coll) end)
{_, t1} = :erlang.statistics(:runtime)
{_, t2} = :erlang.statistics(:wall_clock)
u1 = t1 * 1000/n
u2 = t2 * 1000/n
IO.puts("code exec time #{u1} (#{u2}) microseconds")
end
end
defmodule GuardsTest do
def odds_and_evens_acc(l) do
odds_and_evens_acc(l,[],[])
end
def odds_and_evens_acc([h|t], odds, evens) when rem(h,2) == 0 do
odds_and_evens_acc(t, odds, [h|evens])
end
def odds_and_evens_acc([h|t], odds, evens) when rem(h,2) == 1 do
odds_and_evens_acc(t, [h|odds], evens)
end
def odds_and_evens_acc([], odds, evens) do
{odds, evens}
end
def benchmark(n \\ 10000) do
coll = Enum.into(1..1000,[])
:erlang.statistics(:runtime)
:erlang.statistics(:wall_clock)
Enum.each(1..n, fn(_i)-> odds_and_evens_acc(coll) end)
{_, t1} = :erlang.statistics(:runtime)
{_, t2} = :erlang.statistics(:wall_clock)
u1 = t1 * 1000/n
u2 = t2 * 1000/n
IO.puts("code exec time #{u1} (#{u2}) microseconds")
end
end