1 -module(beam_stats_delta).
11 , of_context_switches/1
14 , of_process_info_reductions/2
18 { erlang_statistics :: ets:tid()
19 , erlang_process_info_reductions :: ets:tid()
36 ets:new(beam_stats_delta_erlang_statistics, Options)
37 , erlang_process_info_reductions =
38 ets:new(beam_stats_delta_erlang_process_info_reductions, Options)
44 { erlang_statistics = TidErlangStatistics
45 , erlang_process_info_reductions = TidErlangProcessInfoReductions
48 true = ets:delete(TidErlangStatistics),
49 true = ets:delete(TidErlangProcessInfoReductions),
54 gc(?T{erlang_process_info_reductions=Table}=T) ->
58 ; FirstPid when is_pid(FirstPid) ->
62 -spec gc(t(), pid()) ->
64 gc(?T{erlang_process_info_reductions=Table}=T, Pid) ->
65 Next = ets:next(Table, Pid),
66 case beam_stats_source:erlang_is_process_alive(Pid)
68 ; false -> ets:delete(Table, Pid)
73 ; NextPid when is_pid(NextPid) ->
77 -spec of_context_switches(t()) ->
79 of_context_switches(?T{erlang_statistics=Table}) ->
80 Key = context_switches,
81 {Current, 0} = beam_stats_source:erlang_statistics(Key),
82 delta(Table, Key, Current).
85 { {io_bytes_in , non_neg_integer()}
86 , {io_bytes_out , non_neg_integer()}
88 of_io(?T{erlang_statistics=Table}) ->
91 , {output , CurrentOut}
92 } = beam_stats_source:erlang_statistics(Key),
93 DeltaIn = delta(Table, io_bytes_in , CurrentIn),
94 DeltaOut = delta(Table, io_bytes_out, CurrentOut),
95 { {io_bytes_in , DeltaIn}
96 , {io_bytes_out , DeltaOut}
99 % We can get between-calls-delta directly from erlang:statistics(reductions),
100 % but then if some other process also calls it - we'll get incorrect data on
102 % Managing deltas ourselves here, will at least reduce the possible callers to
103 % only those with knowledge of our table ID.
104 -spec of_reductions(t()) ->
106 of_reductions(?T{erlang_statistics=Table}) ->
108 {Current, _} = beam_stats_source:erlang_statistics(Key),
109 delta(Table, Key, Current).
111 -spec of_process_info_reductions(t(), pid()) ->
112 hope_option:t(non_neg_integer()).
113 of_process_info_reductions(?T{erlang_process_info_reductions=Table}, Pid) ->
114 case beam_stats_source:erlang_process_info(Pid, reductions)
117 ; {reductions, Current} ->
118 Delta = delta(Table, Pid, Current),
122 -spec delta(ets:tid(), Key, non_neg_integer()) ->
124 when Key :: atom() | pid().
125 delta(Table, Key, CurrentTotal) ->
126 PreviousTotalOpt = find(Table, Key),
127 PreviousTotal = hope_option:get(PreviousTotalOpt, 0),
128 save(Table, Key, CurrentTotal),
129 CurrentTotal - PreviousTotal.
131 -spec find(ets:tid(), term()) ->
132 hope_option:t(term()).
134 case ets:lookup(Table, K)
136 ; [{K, V}] -> {some, V}
139 -spec save(ets:tid(), term(), term()) ->
142 true = ets:insert(Table, {K, V}),