Skip to content

Instantly share code, notes, and snippets.

@alco
Last active April 22, 2018 19:44
Show Gist options
  • Save alco/014b72e3d048a12347c5 to your computer and use it in GitHub Desktop.
Save alco/014b72e3d048a12347c5 to your computer and use it in GitHub Desktop.
defmodule HammingBench do
use Benchfella
use Bitwise
@n Stream.repeatedly(fn -> Enum.random [0, 1] end)
|> Enum.take(100_000)
|> Enum.join
|> String.to_integer(2)
bench "CharlesO" do
Enum.count(Integer.to_char_list(@n,2),&(&1===49))
end
bench "Patrick Oscity" do
for(<<bit::1 <- :binary.encode_unsigned(@n)>>, do: bit) |> Enum.sum
end
bench "alco byte lookup table" do
sum_bytes(:binary.encode_unsigned(@n))
end
bench "alco binary sum bits" do
sum_bits(:binary.encode_unsigned(@n))
end
bench "alco shift" do
shift_sum(@n)
end
###
defp sum_bytes(binary) do
sum_bytes(binary, 0)
end
defp sum_bytes(<<byte::8>> <> rest, sum) do
sum_bytes(rest, sum + lookup_hamming(byte))
end
defp sum_bytes(<<>>, sum) do
sum
end
for byte <- 0..255 do
sum = (for <<bit::1 <- :binary.encode_unsigned(byte)>>, do: bit) |> Enum.sum
defp lookup_hamming(unquote(byte)), do: unquote(sum)
end
###
defp sum_bits(binary) do
sum_bits(binary, 0)
end
defp sum_bits(<<>>, sum) do
sum
end
defp sum_bits(<<bit::1, rest::bitstring>>, sum) do
sum_bits(rest, sum + bit)
end
###
defp shift_sum(n) do
shift_sum(n, 0)
end
defp shift_sum(0, sum) do
sum
end
defp shift_sum(n, sum) do
lsb = band(n, 1)
shift_sum(n >>> 1, sum + lsb)
end
end
$ mix bench
Settings:
duration: 1.0 s
## HammingBench
[22:43:28] 1/5: alco shift
[22:43:29] 2/5: alco byte lookup table
[22:43:32] 3/5: alco binary sum bits
[22:43:34] 4/5: Patrick Oscity
[22:43:37] 5/5: CharlesO
Finished in 14.38 seconds
## HammingBench
alco byte lookup table 10000 268.37 µs/op
alco binary sum bits 1000 1637.74 µs/op
Patrick Oscity 500 4481.21 µs/op
alco shift 10 143481.30 µs/op
CharlesO 1 5253071.00 µs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment