-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathsort_vs_sort_by.exs
More file actions
38 lines (31 loc) · 835 Bytes
/
sort_vs_sort_by.exs
File metadata and controls
38 lines (31 loc) · 835 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
defmodule Card, do: defstruct([:rank, :suit])
defmodule Sort.Fast do
def sort(enumerable), do: Enum.sort(enumerable)
end
defmodule Sort.Medium do
def sort(enumerable), do: Enum.sort(enumerable, &(&1.rank <= &2.rank))
end
defmodule Sort.Slow do
def sort(enumerable), do: Enum.sort_by(enumerable, & &1.rank)
end
defmodule Sort.Benchmark do
def benchmark do
Benchee.run(
%{
"sort/1" => fn -> bench(Sort.Fast) end,
"sort/2" => fn -> bench(Sort.Medium) end,
"sort_by/2" => fn -> bench(Sort.Slow) end
},
time: 10,
print: [fast_warning: false]
)
end
defp bench(module) do
cards =
Enum.map(1..100, fn _ ->
%Card{rank: Enum.random(0..100), suit: Enum.random(~w[red green blue]a)}
end)
module.sort(cards)
end
end
Sort.Benchmark.benchmark()