Skip to content

Instantly share code, notes, and snippets.

@davisp
Last active March 22, 2022 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davisp/7bd032789ef225b4086302de3da6b056 to your computer and use it in GitHub Desktop.
Save davisp/7bd032789ef225b4086302de3da6b056 to your computer and use it in GitHub Desktop.
Erlang Compiler Stack Reference Regression
-module(stack_test).
-export([
run/0
]).
run() ->
run(7500, 0.0008).
run(Depth, BranchChance) ->
rand:seed(exrop, {1647,841737,351137}),
Tree = node(Depth, BranchChance),
erlang:garbage_collect(),
MPid = spawn_mem_sampler(self(), 500),
T1 = erlang:monotonic_time(),
visit(Tree, sets:new()),
T2 = erlang:monotonic_time(),
Max = get_max_mem(MPid),
unlink(MPid),
exit(MPid, kill),
{deltaT(T2, T1), Max}.
visit([], Seen) ->
{sets:add_element(rand:uniform(), Seen), ignore1, ignore2};
visit(Children, Seen0) ->
Seen1 = sets:add_element(rand:uniform(), Seen0),
lists:foldl(fun(Child, Acc) ->
{SeenAcc, Ignore1, Ignore2} = Acc,
{NewSeenAcc, _, _} = visit(Child, SeenAcc),
{NewSeenAcc, Ignore1, Ignore2}
end, {Seen1, ignore1, ignore2}, Children).
node(0, _) ->
[];
node(Depth, BranchChance) ->
case rand:uniform() < BranchChance of
true ->
[
node(Depth - 1, BranchChance),
node(Depth - 1, BranchChance)
];
false ->
[node(Depth - 1, BranchChance)]
end.
deltaT(T0, T1) ->
erlang:convert_time_unit(T0 - T1, native, millisecond).
spawn_mem_sampler(Pid, DtMsec) ->
spawn_link(fun() -> mem_sampler(Pid, DtMsec, mem_mb(Pid)) end).
mem_sampler(Pid, DtMsec, Max0) ->
timer:sleep(DtMsec),
Max = max(mem_mb(Pid), Max0),
receive
{get_mem, From} ->
From ! {mem_max, Max}
after 0 ->
ok
end,
mem_sampler(Pid, DtMsec, Max).
mem_mb(Pid) ->
{memory, Words} = erlang:process_info(Pid, memory),
Bytes = Words * erlang:system_info(wordsize),
Bytes / (1024 * 1024).
get_max_mem(Pid) ->
Pid ! {get_mem, self()},
receive {mem_max, Max} -> Max end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment