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()
35 { erlang_statistics = ets:new(beam_stats_delta_erlang_statistics, Options)
36 , erlang_process_info_reductions =
37 ets:new(beam_stats_delta_erlang_process_info_reductions, Options)
43 { erlang_statistics = TidErlangStatistics
44 , erlang_process_info_reductions = TidErlangProcessInfoReductions
47 true = ets:delete(TidErlangStatistics),
48 true = ets:delete(TidErlangProcessInfoReductions),
53 gc(?T{erlang_process_info_reductions=Table}=T) ->
57 ; FirstPid when is_pid(FirstPid) ->
61 -spec gc(t(), pid()) ->
63 gc(?T{erlang_process_info_reductions=Table}=T, Pid) ->
64 Next = ets:next(Table, Pid),
65 case beam_stats_source:erlang_is_process_alive(Pid)
67 ; false -> ets:delete(Table, Pid)
72 ; NextPid when is_pid(NextPid) ->
76 -spec of_context_switches(t()) ->
78 of_context_switches(?T{erlang_statistics=Table}) ->
79 Key = context_switches,
80 {Current, 0} = beam_stats_source:erlang_statistics(Key),
81 delta(Table, Key, Current).
84 { {io_bytes_in , non_neg_integer()}
85 , {io_bytes_out , non_neg_integer()}
87 of_io(?T{erlang_statistics=Table}) ->
90 , {output , CurrentOut}
91 } = beam_stats_source:erlang_statistics(Key),
92 DeltaIn = delta(Table, io_bytes_in , CurrentIn),
93 DeltaOut = delta(Table, io_bytes_out, CurrentOut),
94 { {io_bytes_in , DeltaIn}
95 , {io_bytes_out , DeltaOut}
98 % We can get between-calls-delta directly from erlang:statistics(reductions),
99 % but then if some other process also calls it - we'll get incorrect data on
101 % Managing deltas ourselves here, will at least reduce the possible callers to
102 % only those with knowledge of our table ID.
103 -spec of_reductions(t()) ->
105 of_reductions(?T{erlang_statistics=Table}) ->
107 {Current, _} = beam_stats_source:erlang_statistics(Key),
108 delta(Table, Key, Current).
110 -spec of_process_info_reductions(t(), pid()) ->
111 hope_option:t(non_neg_integer()).
112 of_process_info_reductions(?T{erlang_process_info_reductions=Table}, Pid) ->
113 case beam_stats_source:erlang_process_info(Pid, reductions)
116 ; {reductions, Current} ->
117 Delta = delta(Table, Pid, Current),
121 -spec delta(ets:tid(), Key, non_neg_integer()) ->
123 when Key :: atom() | pid().
124 delta(Table, Key, CurrentTotal) ->
125 PreviousTotalOpt = find(Table, Key),
126 PreviousTotal = hope_option:get(PreviousTotalOpt, 0),
127 save(Table, Key, CurrentTotal),
128 CurrentTotal - PreviousTotal.
130 -spec find(ets:tid(), term()) ->
131 hope_option:t(term()).
133 case ets:lookup(Table, K)
135 ; [{K, V}] -> {some, V}
138 -spec save(ets:tid(), term(), term()) ->
141 true = ets:insert(Table, {K, V}),