Skip to content

Instantly share code, notes, and snippets.

@lunks
Created August 13, 2024 16:12
Show Gist options
  • Select an option

  • Save lunks/2a93b7f710e7de7444b45883288a0d3e to your computer and use it in GitHub Desktop.

Select an option

Save lunks/2a93b7f710e7de7444b45883288a0d3e to your computer and use it in GitHub Desktop.

Revisions

  1. lunks revised this gist Aug 13, 2024. No changes.
  2. lunks created this gist Aug 13, 2024.
    38 changes: 38 additions & 0 deletions bench.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    defmodule BenchmarkReduceWhile do
    def has_duplicates?(list) do
    Enum.reduce_while(list, %MapSet{}, fn x, seen ->
    if MapSet.member?(seen, x) do
    {:halt, true}
    else
    {:cont, MapSet.put(seen, x)}
    end
    end) || false
    end
    end

    defmodule BenchmarkRecursion do
    def has_duplicates?(list), do: has_duplicates?(list, %MapSet{})

    defp has_duplicates?([], _), do: false

    defp has_duplicates?([head | tail], seen) do
    MapSet.member?(seen, head) || has_duplicates?(tail, MapSet.put(seen, head))
    end
    end

    defmodule BenchmarkTest do
    def run do
    list = Enum.to_list(1..10000) ++ [5000]

    Benchee.run(
    %{
    "reduce_while" => fn -> BenchmarkReduceWhile.has_duplicates?(list) end,
    "recursion" => fn -> BenchmarkRecursion.has_duplicates?(list) end
    },
    time: 20,
    warmup: 5
    )
    end
    end

    BenchmarkTest.run()
    29 changes: 29 additions & 0 deletions result.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    Operating System: Linux
    CPU Information: AMD Ryzen Threadripper 3970X 32-Core Processor
    Number of Available Cores: 32
    Available memory: 16 GB
    Elixir 1.16.2
    Erlang 26.2.5
    JIT enabled: true

    Benchmark suite executing with the following configuration:
    warmup: 5 s
    time: 20 s
    memory time: 0 ns
    reduction time: 0 ns
    parallel: 1
    inputs: none specified
    Estimated total run time: 50 s

    Benchmarking recursion ...
    Benchmarking reduce_while ...
    Calculating statistics...
    Formatting results...

    Name ips average deviation median 99th %
    recursion 404.36 2.47 ms ±13.41% 2.38 ms 3.52 ms
    reduce_while 372.01 2.69 ms ±12.97% 2.53 ms 3.65 ms

    Comparison:
    recursion 404.36
    reduce_while 372.01 - 1.09x slower +0.22 ms