Skip to content

Instantly share code, notes, and snippets.

@pertsevds
Forked from dominicletz/find_fragmentation.erl
Created August 31, 2023 04:52
Show Gist options
  • Save pertsevds/ab20d3efddb4a96ad2f1417fc6cc8d11 to your computer and use it in GitHub Desktop.
Save pertsevds/ab20d3efddb4a96ad2f1417fc6cc8d11 to your computer and use it in GitHub Desktop.
Erlang script to show used vs. allocated carrier sizes to find impact of memory fragmentation
f().
Str = fun(X) -> io_lib:format("~p", [X]) end.
Percent = fun
(A, 0) -> "100%";
(A, B) -> [Str(round(100*A/B)), "%"]
end.
Get = fun
(undefined, _Key) -> 0;
(Info, Key) ->
element(2, lists:keyfind(Key, 1, Info))
end.
GetAlloc = fun
(undefined) -> 0;
(List) -> element(3, hd(List))
end.
Allocators = [sys_alloc, temp_alloc, sl_alloc, std_alloc, ll_alloc,
eheap_alloc, ets_alloc, fix_alloc, literal_alloc, exec_alloc,
binary_alloc, driver_alloc, mseg_alloc].
lists:foreach(fun(Alloc) ->
Info = (catch erlang:system_info({allocator, Alloc})),
if is_list(Info) ->
{Allocated, Used, Calls} = lists:foldl(
fun({instance, _Nr, Stats}, {Al, Us, Ca}) ->
Mbcs = proplists:get_value(mbcs, Stats),
Allocated = Get(Mbcs, carriers_size),
Used = case lists:keyfind(blocks, 1, proplists:get_value(mbcs, Stats, [])) of
false -> Get(Mbcs, blocks_size);
{blocks, _, _, _} -> Get(Mbcs, blocks_size);
{blocks, List} -> lists:foldl(fun({_, Other}, Sum) -> Sum + Get(Other, size) end, 0, List)
end,
Calls = GetAlloc(proplists:get_value(calls, Stats)),
{Allocated + Al, Used + Us, Calls + Ca};
(_, {Al, Us, Ca}) -> {Al, Us, Ca}
end,
{0, 0, 0},
Info
),
Waste = Allocated - Used,
io:format(
"~-14s got ~10s used of ~10s alloc (~4s) = ~10s waste @ ~10s calls~n",
[Alloc, Str(Used), Str(Allocated), Percent(Used, Allocated), Str(Waste), Str(Calls)]
);
true ->
io:format("~-14s is disabled~n", [Alloc])
end
end, Allocators).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment