Created
November 1, 2017 22:26
-
-
Save wisq/820b54068beb0b871b42c2a608c9df56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting that body_call is the fastest! Must be an implementation detail responsible. ;)