aboutsummaryrefslogtreecommitdiffstats
path: root/lib/runtime_tools/src/msacc.erl
blob: 0d9b2690e51e8934d873548703dfc4d610e43cfe (plain) (blame)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2014-2016. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%

%%
%% @doc Microstate accounting utility function
%%
%%	This module provides a user interface for analysing
%%      erlang:statistics(microstate_accounting) data.
%%

-module(msacc).
-export([available/0, start/0, start/1, stop/0, reset/0, to_file/1,
         from_file/1, stats/0, stats/2, print/0, print/1, print/2,
         print/3]).

-type msacc_data() :: [msacc_data_thread()].

-type msacc_data_thread() :: #{ '$type' := msacc_data,
                                type := msacc_type(), id := msacc_id(),
                                counters := msacc_data_counters() }.
-type msacc_data_counters() :: #{ msacc_state() => non_neg_integer()}.

-type msacc_stats() :: [msacc_stats_thread()].
-type msacc_stats_thread() :: #{ '$type' := msacc_stats,
                                 type := msacc_type(), id := msacc_id(),
                                 system := float(),
                                 counters := msacc_stats_counters()}.
-type msacc_stats_counters() :: #{ msacc_state() => #{ thread := float(),
                                                       system := float()}}.


-type msacc_type() :: scheduler | aux | async.
-type msacc_id() :: non_neg_integer().
-type msacc_state() :: alloc | aux | bif | busy_wait | check_io |
                       emulator | ets | gc | gc_fullsweep | nif |
                       other | port | send | sleep | timers.

-type msacc_print_options() :: #{ system => boolean() }.

-spec available() -> boolean().
available() ->
    try
        [_|_] = erlang:statistics(microstate_accounting),
        true
    catch _:_ ->
            false
    end.

-spec start() -> boolean().
start() ->
    erlang:system_flag(microstate_accounting, true).

-spec stop() -> boolean().
stop() ->
    erlang:system_flag(microstate_accounting, false).

-spec reset() -> boolean().
reset() ->
    erlang:system_flag(microstate_accounting, reset).

-spec start(Time) -> true when
      Time :: timeout().
start(Tmo) ->
    stop(), reset(), start(),
    timer:sleep(Tmo),
    stop().

-spec to_file(Filename) -> ok | {error, file:posix()} when
      Filename :: file:name_all().
to_file(Filename) ->
    file:write_file(Filename, io_lib:format("~p.~n",[stats()])).

-spec from_file(Filename) -> msacc_data() when
      Filename :: file:name_all().
from_file(Filename) ->
    {ok, [Stats]} = file:consult(Filename),
    Stats.

-spec print() -> ok.
print() ->
    print(stats()).

-spec print(DataOrStats) -> ok when
      DataOrStats :: msacc_data() | msacc_stats().
print(Stats) ->
    print(Stats, #{}).

-spec print(DataOrStats, Options) -> ok when
      DataOrStats :: msacc_data() | msacc_stats(),
      Options :: msacc_print_options().
print(Stats, Options) ->
    print(group_leader(), Stats, Options).

-spec print(FileOrDevice, DataOrStats, Options) -> ok when
      FileOrDevice :: file:filename() | io:device(),
      DataOrStats :: msacc_data() | msacc_stats(),
      Options :: msacc_print_options().
print(Filename, Stats, Options) when is_list(Filename) ->
    case file:open(Filename,[write]) of
        {ok, D} -> print(D, Stats, Options),file:close(D);
        Error -> Error
    end;
print(Device, Stats, Options) ->
    DefaultOpts = #{ system => false },
    print_int(Device, Stats, maps:merge(DefaultOpts, Options)).
print_int(Device, [#{ '$type' := msacc_data, id := _Id }|_] = Stats, Options) ->
    TypeStats = stats(type, Stats),
    io:format(Device, "~s", [print_stats_overview(Stats, Options)]),
    io:format(Device, "~s", [print_stats_header(Stats, Options)]),
    io:format(Device, "~s", [print_stats_threads(
                               stats(realtime, Stats), Options)]),
    io:format(Device, "~s", [print_stats_type(
                               stats(realtime, TypeStats), Options)]);
print_int(Device, [#{ '$type' := msacc_data }|_] = Stats, Options) ->
    io:format(Device, "~s", [print_stats_header(Stats, Options)]),
    io:format(Device, "~s", [print_stats_type(
                               stats(realtime, Stats), Options)]);
print_int(Device, [#{ '$type' := msacc_stats, id := _Id }|_] = Stats,Options) ->
    io:format(Device, "~s", [print_stats_header(Stats, Options)]),
    io:format(Device, "~s", [print_stats_threads(Stats, Options)]),
    io:format(Device, "~s", [print_stats_type(
                               msacc:stats(type, Stats), Options)]);
print_int(Device, [#{ '$type' := msacc_stats }|_] = Stats, Options) ->
    io:format(Device, "~s", [print_stats_header(Stats, Options)]),
    io:format(Device, "~s", [print_stats_type(Stats, Options)]).


-spec stats() -> msacc_data().
stats() ->
    Fun = fun F(K,{PerfCount,StateCount}) ->
                %% Need to handle ERTS_MSACC_STATE_COUNTERS
                {F(K,PerfCount),StateCount};
              F(_K,PerfCount) ->
                erlang:convert_time_unit(PerfCount, perf_counter, 1000000)
        end,
    UsStats = lists:map(
                fun(#{ counters := Cnt } = M) ->
                        UsCnt = maps:map(Fun,Cnt),
                        M#{ '$type' => msacc_data, counters := UsCnt }
                end, erlang:statistics(microstate_accounting)),
    statssort(UsStats).

-spec stats(Analysis, Stats) -> non_neg_integer() when
      Analysis :: system_realtime | system_runtime,
      Stats :: msacc_data();
           (Analysis, Stats) -> msacc_stats() when
      Analysis :: realtime | runtime,
      Stats :: msacc_data();
           (Analysis, StatsOrData) -> msacc_data() | msacc_stats() when
      Analysis :: type,
      StatsOrData :: msacc_data() | msacc_stats().
stats(system_realtime, Stats) ->
    lists:foldl(fun(#{ counters := Cnt }, Acc) ->
                        get_total(Cnt, Acc)
                end, 0, Stats);
stats(system_runtime, Stats) ->
    lists:foldl(fun(#{ counters := Cnt }, Acc) ->
                        get_total(maps:remove(sleep, Cnt), Acc)
                end, 0, Stats);
stats(realtime, Stats) ->
    RealTime = stats(system_realtime, Stats),
    statssort([get_thread_perc(Thread, RealTime) || Thread <- Stats]);
stats(runtime, Stats) ->
    RunTime = stats(system_runtime, Stats),
    statssort([get_thread_perc(T#{ counters := maps:remove(sleep,Cnt)}, RunTime)
                               || T = #{ counters := Cnt } <- Stats]);
stats(type, Stats) ->
    statssort(merge_threads(Stats, [])).

print_stats_overview(Stats, _Options) ->
    RunTime = stats(system_runtime, Stats),
    RealTime = stats(system_realtime, Stats) div length(Stats),
    SchedStats = [S || #{ type := scheduler } = S <- Stats],
    AvgSchedRunTime = stats(system_runtime, SchedStats) div length(SchedStats),
    NumSize = if
                  RealTime > RunTime -> length(integer_to_list(RealTime));
                  true -> length(integer_to_list(RunTime))
              end,
    [io_lib:format("Average thread real-time    : ~*B us~n",
                   [NumSize, RealTime]),
     io_lib:format("Accumulated system run-time : ~*B us~n",
                   [NumSize, RunTime]),
     io_lib:format("Average scheduler run-time  : ~*B us~n",
                   [NumSize, AvgSchedRunTime]),
     io_lib:format("~n",[])].

print_stats_threads(Stats, Options) ->
    [io_lib:format("~nStats per thread:~n", []),
     [print_thread_info(Thread, Options) || Thread <- Stats]].

print_stats_type(Stats, Options) ->
    [io_lib:format("~nStats per type:~n", []),
     [print_thread_info(Thread, Options) || Thread <- Stats]].


print_stats_header([#{ counters := Cnt }|_], #{ system := PrintSys }) ->
    [io_lib:format("~14s", ["Thread"]),
     map(fun(Counter, _) when PrintSys->
                 io_lib:format("~9s     ", [atom_to_list(Counter)]);
            (Counter, _) ->
                 io_lib:format("~9s", [atom_to_list(Counter)])
         end, Cnt),
     io_lib:format("~n",[])].

print_thread_info(#{ '$type' := msacc_stats,
                     counters := Cnt } = Thread, #{ system := PrintSys }) ->
    [case maps:find(id, Thread) of
        error ->
            io_lib:format("~14s", [atom_to_list(maps:get(type, Thread))]);
        {ok, Id} ->
            io_lib:format("~10s(~2B)", [atom_to_list(maps:get(type,Thread)),Id])
    end,
    map(fun(_Key, #{ thread := ThreadPerc, system := SystemPerc }) when PrintSys ->
                io_lib:format("~6.2f%(~4.1f%)", [ThreadPerc, SystemPerc]);
           (_Key, #{ thread := ThreadPerc }) ->
                io_lib:format("~8.2f%", [ThreadPerc])
             end, Cnt),
    io_lib:format("~n",[])].

get_total(Cnt, Base) ->
    maps:fold(fun(_, {Val,_}, Time) ->
                      %% Have to handle ERTS_MSACC_STATE_COUNTERS
                      Time + Val;
                 (_, Val, Time) -> Time + Val
              end, Base, Cnt).

get_thread_perc(#{ '$type' := msacc_data, counters := Cnt } = Thread,
                SystemTime) ->
    ThreadTime = get_total(Cnt, 0),
    Thread#{ '$type' := msacc_stats,
             system => percentage(ThreadTime,SystemTime),
             counters => get_thread_perc(Cnt, ThreadTime, SystemTime)}.
get_thread_perc(Cnt, ThreadTime, SystemTime) ->
    maps:map(fun F(Key, {Val, C}) ->
                    M = F(Key, Val),
                    M#{ cnt => C };
                 F(_Key, Val) ->
                    #{ thread => percentage(Val, ThreadTime),
                       system => percentage(Val, SystemTime) }
            end, Cnt).

%% This code is a little bit messy as it has to be able to deal with
%% both [msacc_data()] and [msacc_stats()].
merge_threads([#{ '$type' := msacc_stats,
                  type := Type,
                  counters := Cnt } = M0|R], Acc) ->
    case keyfind(type, Type, Acc) of
        false ->
            merge_threads(R, [maps:remove(id,M0#{ threads => 1 })|Acc]);
        #{ '$type' := msacc_stats, counters := Cnt0,
           threads := Threads, system := System } = M ->
            NewMap = M#{ counters := add_counters(Cnt, Cnt0),
                         system := System + maps:get(system, M0),
                         threads := Threads + 1},
            NewAcc = keyreplace(type, Type, NewMap, Acc),
            merge_threads(R, NewAcc)
    end;
merge_threads([], [#{ '$type' := msacc_stats,
                      system := System,
                      threads := Threads,
                      counters := Cnt} = M0|R]) ->
    Counters = maps:map(fun(_,#{ thread := Thr } = Map) ->
                                Map#{ thread := Thr / Threads }
                        end, Cnt),
    M = maps:remove(threads, M0),
    [M#{ system := System, counters := Counters} | merge_threads([],R)];
merge_threads([], []) ->
    [];
%% The clauses below deal with msacc_data()
merge_threads([#{ '$type' := msacc_data,
                  type := Type,
                  counters := Cnt } = M0|R], Acc) ->
    case keyfind(type, Type, Acc) of
        false ->
            merge_threads(R, [maps:remove(id,M0)|Acc]);
        #{ '$type' := msacc_data, counters := Cnt0 } = M ->
            NewMap = M#{ counters := add_counters(Cnt, Cnt0) },
            NewAcc = keyreplace(type, Type, NewMap, Acc),
            merge_threads(R, NewAcc)
    end;
merge_threads([], Acc) ->
    Acc.

add_counters(M1, M2) ->
    maps:map(
      fun(Key, #{ thread := Thr1, system := Sys1, cnt := Cnt1}) ->
              %% Have to handle ERTS_MSACC_STATE_COUNTERS
              #{ thread := Thr2, system := Sys2, cnt := Cnt2} = maps:get(Key, M2),
              #{ thread => Thr1 + Thr2, system => Sys1 + Sys2,
                 cnt => Cnt1 + Cnt2 };
         (Key, #{ thread := Thr1, system := Sys1}) ->
              #{ thread := Thr2, system := Sys2} = maps:get(Key, M2),
              #{ thread => Thr1 + Thr2, system => Sys1 + Sys2};
         (Key, {V1,C1}) ->
              %% Have to handle ERTS_MSACC_STATE_COUNTERS
              {V2,C2} = maps:get(Key, M2),{V1+V2,C1+C2};
         (Key, V1) -> maps:get(Key, M2) + V1
      end, M1).

percentage(Divident, Divisor) ->
    if Divisor == 0 andalso Divident /= 0 ->
            100.0;
        Divisor == 0 ->
            0.0;
       true ->
            Divident / Divisor * 100
    end.

keyfind(Key, Value, [H|T]) ->
    case maps:find(Key, H) of
        {ok, Value} ->
            H;
        _ ->
            keyfind(Key, Value, T)
    end;
keyfind(_, _, []) ->
    false.

keyreplace(Key, Value, NewMap, [H|T]) ->
    case maps:find(Key, H) of
        {ok, Value} ->
            [NewMap|T];
        _ ->
            [H|keyreplace(Key, Value, NewMap, T)]
    end;
keyreplace(_, _, _, []) ->
    [].

statssort(Stats) ->
    lists:sort(fun(#{ type := Type1, id := Id1},
                   #{ type := Type2, id := Id2}) ->
                       {Type1, Id1} < {Type2, Id2};
                  (#{ type := Type1}, #{ type := Type2}) ->
                       Type1 < Type2
               end, Stats).

map(Fun,Map) ->
    [ Fun(K,V) || {K,V} <- maps:to_list(Map) ].