Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Untitled notebook

nimble_parsec.livemd

Untitled notebook

Mix.install([:benchee])

Section

defmodule ParseInt do
  def parse_new(<<3::4, x0::4, 3::4, x1::4, 3::4, x2::4, 3::4, x3::4>>)
      when x0 < 10 and x1 < 10 and x2 < 10 and x3 < 10 do
    x3 + x2 * 10 + x1 * 100 + x0 * 1000
  end

  def nimble(<>)
      when x0 >= 48 and x0 <= 57 and (x1 >= 48 and x1 <= 57) and
             (x2 >= 48 and x2 <= 57) and (x3 >= 48 and x3 <= 57) do
    x3 - 48 + (x2 - 48) * 10 + (x1 - 48) * 100 + (x0 - 48) * 1000
  end
end

{ParseInt.parse_new("1123"), ParseInt.nimble("1123")}
list = Enum.map(1000..9999, &amp;to_string(&amp;1))

Benchee.run(
  %{
    "original" => fn -> Enum.map(list, &amp;ParseInt.nimble(&amp;1)) end,
    "half byte" => fn -> Enum.map(list, &amp;ParseInt.parse_new(&amp;1)) end
  },
  time: 10,
  memory_time: 2
)