Skip to content

Instantly share code, notes, and snippets.

@davisp
Last active March 21, 2022 18:40
Show Gist options
  • Save davisp/16966873a6725fedc052761223415421 to your computer and use it in GitHub Desktop.
Save davisp/16966873a6725fedc052761223415421 to your computer and use it in GitHub Desktop.
-module(slow_tuples).
-export([
run/0
]).
run() ->
Vals = gen(),
erlang:garbage_collect(),
MPid = spawn_mem_sampler(self(), 500),
T1 = erlang:monotonic_time(),
loop({10000, Vals, []}),
T2 = erlang:monotonic_time(),
Max = get_max_mem(MPid),
erlang:garbage_collect(),
unlink(MPid),
exit(MPid, kill),
{dt(T2, T1), Max}.
gen() ->
gen(300000, sets:new()).
gen(0, Vals) ->
Vals;
gen(N, Vals) ->
Bin = <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, N:32>>,
gen(N - 1, sets:add_element(Bin, Vals)).
loop({0, _Vals, _Stuff}) ->
ok;
loop({N, Vals, Stuff}) ->
loop({N - 1, Vals, [N | Stuff]}).
dt(T0, T1) ->
erlang:convert_time_unit(T0-T1, native, second).
mem_mb(Pid) ->
{memory, Words} = erlang:process_info(Pid, memory),
Bytes = Words * 8,
Bytes / (1024 * 1024).
get_max_mem(Pid) ->
Pid ! {get_mem, self()},
receive {mem_max, Max} -> Max end.
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment