2024 day 12 - make p1 faster

This commit is contained in:
Caleb Webber 2024-12-12 15:01:12 -05:00
parent 7aba3bab17
commit 04ce5b915f

View file

@ -1,5 +1,13 @@
# AOC2024 Day 12
```elixir
Mix.install(
[
{:kino_benchee, "0.1.0"}
]
)
```
## Section
```elixir
@ -186,19 +194,24 @@ defmodule Crawl do
end |> elem(1)
end
def pricep1(regions) do
def pricep1(regions, tiles, grid) do
for region <- regions, reduce: 0 do
acc ->
area = region |> MapSet.size()
perimeter = 4*area - (region |> MapSet.to_list() |> EnumUtil.pick_n(2) |> Stream.map(
fn [{a,b},{x,y}] ->
if (a == x and abs(b-y) == 1) or (b == y and abs(a-x) == 1) do
2
else
0
end
end
) |> Enum.sum())
perimeter = region |> MapSet.to_list() |> Enum.map(
fn tile ->
Grid2D.directions(:straight)
|> Enum.reduce(
0,
fn d, acc ->
nb = Grid2D.add(d, tile)
if !Grid2D.is_in_grid?(nb, grid) or Map.get(tiles, nb) != Map.get(tiles, tile) do
acc + 1
else
acc
end
end)
end) |> Enum.sum()
acc + area*perimeter
end
end
@ -263,9 +276,56 @@ regions = Crawl.crawl(tiles, grid)
```
```elixir
Crawl.pricep1(regions)
Benchee.run(%{
"p1": fn -> Crawl.pricep1(regions, tiles, grid) end,
p2: fn -> Crawl.pricep2(regions, tiles, grid) end
})
```
```elixir
Crawl.pricep2(regions, tiles, grid)
<!-- livebook:{"output":true} -->
```
warning: found quoted keyword "p1" but the quotes are not required. Note that keywords are always atoms, even when quoted. Similar to atoms, keywords made exclusively of ASCII letters, numbers, and underscores and not beginning with a number do not require quotes
└─ Library/Application Support/livebook/autosaved/2024_12_12/15_42_5s6a/aoc2024_day_12.livemd#cell:fma2uf6b3e4jblnu:2:4
Error trying to determine erlang version enoent, falling back to overall OTP version
Warning: the benchmark p1 is using an evaluated function.
Evaluated functions perform slower than compiled functions.
You can move the Benchee caller to a function in a module and invoke `Mod.fun()` instead.
Alternatively, you can move the benchmark into a benchmark.exs file and run mix run benchmark.exs
Warning: the benchmark p2 is using an evaluated function.
Evaluated functions perform slower than compiled functions.
You can move the Benchee caller to a function in a module and invoke `Mod.fun()` instead.
Alternatively, you can move the benchmark into a benchmark.exs file and run mix run benchmark.exs
Operating System: macOS
CPU Information: Apple M1 Pro
Number of Available Cores: 10
Available memory: 16 GB
Elixir 1.17.2
Erlang 27
JIT enabled: true
Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 0 ns
reduction time: 0 ns
parallel: 1
inputs: none specified
Estimated total run time: 14 s
Benchmarking p1 ...
Benchmarking p2 ...
Calculating statistics...
Formatting results...
Name ips average deviation median 99th %
p1 93.85 10.66 ms ±7.19% 10.61 ms 12.65 ms
p2 45.60 21.93 ms ±4.21% 21.87 ms 24.31 ms
Comparison:
p1 93.85
p2 45.60 - 2.06x slower +11.27 ms
```