Skip to content

Instantly share code, notes, and snippets.

@comboy
Created June 15, 2018 20:48
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 comboy/1c1b5c9fbd27d0686f3c171c5901e6b8 to your computer and use it in GitHub Desktop.
Save comboy/1c1b5c9fbd27d0686f3c171c5901e6b8 to your computer and use it in GitHub Desktop.
ops_count = 100_000
max_data_push = 100
{ops, _len} = (0..ops_count) |> Enum.reduce({[], 0}, fn (_, {list, len}) ->
if :rand.uniform(2) == 1 do # push
to_push = :rand.uniform(max_data_push)
{[{:push, :crypto.strong_rand_bytes(to_push)} | list], len + to_push}
else # pull
if len == 0 do
{list, len}
else
to_pull = :rand.uniform(len)
{[{:pull, to_pull} | list ], len - to_pull}
end
end
end)
{micro1, result1} = :timer.tc(fn ->
ops |> Enum.reduce(<<>>, fn (op, queue) ->
case op do
{:push, data} ->
data <> queue
{:pull, num} ->
{_result, queue} = queue |> Binary.split_at(num)
queue
end
end)
end)
{micro2, result2} = :timer.tc(fn ->
ops |> Enum.reduce(Binary.Queue.new(), fn (op, queue) ->
case op do
{:push, data} ->
queue |> Binary.Queue.push(data)
{:pull, num} ->
{_result, queue} = queue |> Binary.Queue.pull(num)
queue
end
end)
end)
IO.puts "utime split: #{micro1}, utime queue: #{micro2}"
IO.puts "results match: #{result1 == result2}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment