Skip to content

Instantly share code, notes, and snippets.

@tony612
Last active February 19, 2019 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tony612/69affe62fdb74af22a3d9a94a68624aa to your computer and use it in GitHub Desktop.
Save tony612/69affe62fdb74af22a3d9a94a68624aa to your computer and use it in GitHub Desktop.
Elixir binary parsing test
defmodule Foo do
def foo1(bin, arg \\ 0) do
case do_foo1(bin) do
{:end, bin} = r ->
{r, arg}
{a, rest} ->
foo1(rest, arg + 1)
end
end
def do_foo1(<<a::8, rest::bits>>) do
{a, rest}
end
def do_foo1(_) do
{:end, <<>>}
end
def foo2(bin, times \\ 0) do
do_foo2(bin, times)
end
def do_foo2(<<a::8, rest::bits>>, times) do
do_foo2(rest, times + 1)
end
def do_foo2(_, times) do
{:end, times}
end
end
IO.inspect Foo.foo1(String.duplicate(<<1>>, 10240))
IO.inspect Foo.foo2(String.duplicate(<<1>>, 10240))
start = System.monotonic_time(:millisecond)
Enum.each(1..1000, fn _ ->
Foo.foo1(String.duplicate(<<1>>, 10240))
end)
finish = System.monotonic_time(:millisecond)
IO.puts "Slow avg for 10KB: #{finish - start}ms"
start = System.monotonic_time(:millisecond)
Enum.each(1..1000, fn _ ->
Foo.foo2(String.duplicate(<<1>>, 10240))
end)
finish = System.monotonic_time(:millisecond)
IO.puts "Fast avg for 10KB: #{finish - start}ms"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment