Skip to content

Instantly share code, notes, and snippets.

@wisq
Created November 1, 2017 22:26
Show Gist options
  • Save wisq/820b54068beb0b871b42c2a608c9df56 to your computer and use it in GitHub Desktop.
Save wisq/820b54068beb0b871b42c2a608c9df56 to your computer and use it in GitHub Desktop.
defmodule Benchmark do
defmacro __using__(_) do
quote do
import Benchmark
def measure(name, function) do
{usecs, retval} = function |> :timer.tc
IO.puts("#{name} took #{usecs} µs")
retval
end
end
end
defmacro benchmark_2(method) do
quote do
test "#{unquote(method)}/2 benchmark" do
input = (1..@size) |> Enum.to_list
output = measure("#{unquote(method)}/2", fn ->
unquote(method)(input, [])
end)
assert input == output
end
end
end
defmacro benchmark_1(method) do
quote do
test "#{unquote(method)}/1 benchmark" do
input = (1..@size) |> Enum.to_list
output = measure("#{unquote(method)}/1", fn ->
unquote(method)(input)
end)
assert input == output
end
end
end
end
defmodule ConsTestTest do
use ExUnit.Case
use Benchmark
@size 100000
def cons_then_reverse([], output), do: output |> Enum.reverse
def cons_then_reverse([item | input], output) do
cons_then_reverse(input, [item | output])
end
benchmark_2(:cons_then_reverse)
def plus_plus([], output), do: output
def plus_plus([item | input], output) do
plus_plus(input, output ++ [item])
end
benchmark_2(:plus_plus)
def enum_concat([], output), do: output
def enum_concat([item | input], output) do
enum_concat(input, Enum.concat(output, [item]))
end
benchmark_2(:enum_concat)
def body_call([]), do: []
def body_call([item | input]) do
[item | body_call(input)]
end
benchmark_1(:body_call)
def list_flatten([], output), do: output |> List.flatten
def list_flatten([item | input], output) do
list_flatten(input, [output | [item]])
end
benchmark_2(:list_flatten)
end
@pmarreck
Copy link

pmarreck commented Nov 1, 2017

Interesting that body_call is the fastest! Must be an implementation detail responsible. ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment