| 1 | -module(beam_stats_delta). |
| 2 | |
| 3 | -export_type( |
| 4 | [ t/0 |
| 5 | ]). |
| 6 | |
| 7 | -export( |
| 8 | [ start/0 |
| 9 | , stop/1 |
| 10 | , of_context_switches/1 |
| 11 | , of_io/1 |
| 12 | ]). |
| 13 | |
| 14 | -record(?MODULE, |
| 15 | { erlang_statistics :: ets:tid() |
| 16 | }). |
| 17 | |
| 18 | -define(T, #?MODULE). |
| 19 | |
| 20 | -opaque t() :: |
| 21 | ?T{}. |
| 22 | |
| 23 | -spec start() -> |
| 24 | t(). |
| 25 | start() -> |
| 26 | Options = |
| 27 | [ set |
| 28 | , public |
| 29 | ], |
| 30 | ?T |
| 31 | { erlang_statistics = ets:new(beam_stats_delta_erlang_statistics, Options) |
| 32 | }. |
| 33 | |
| 34 | -spec stop(t()) -> |
| 35 | {}. |
| 36 | stop(?T |
| 37 | { erlang_statistics = TidErlangStatistics |
| 38 | } |
| 39 | ) -> |
| 40 | true = ets:delete(TidErlangStatistics), |
| 41 | {}. |
| 42 | |
| 43 | -spec of_context_switches(t()) -> |
| 44 | non_neg_integer(). |
| 45 | of_context_switches(?T{erlang_statistics=Table}) -> |
| 46 | Key = context_switches, |
| 47 | {Current, 0} = beam_stats_source:erlang_statistics(Key), |
| 48 | delta(Table, Key, Current). |
| 49 | |
| 50 | -spec of_io(t()) -> |
| 51 | { {io_bytes_in , non_neg_integer()} |
| 52 | , {io_bytes_out , non_neg_integer()} |
| 53 | }. |
| 54 | of_io(?T{erlang_statistics=Table}) -> |
| 55 | Key = io, |
| 56 | { {input , CurrentIn} |
| 57 | , {output , CurrentOut} |
| 58 | } = beam_stats_source:erlang_statistics(Key), |
| 59 | DeltaIn = delta(Table, io_bytes_in , CurrentIn), |
| 60 | DeltaOut = delta(Table, io_bytes_out, CurrentOut), |
| 61 | { {io_bytes_in , DeltaIn} |
| 62 | , {io_bytes_out , DeltaOut} |
| 63 | }. |
| 64 | |
| 65 | -spec delta(ets:tid(), atom(), non_neg_integer()) -> |
| 66 | non_neg_integer(). |
| 67 | delta(Table, Key, CurrentTotal) -> |
| 68 | PreviousTotalOpt = find(Table, Key), |
| 69 | PreviousTotal = hope_option:get(PreviousTotalOpt, 0), |
| 70 | save(Table, Key, CurrentTotal), |
| 71 | CurrentTotal - PreviousTotal. |
| 72 | |
| 73 | -spec find(ets:tid(), term()) -> |
| 74 | hope_option:t(term()). |
| 75 | find(Table, K) -> |
| 76 | case ets:lookup(Table, K) |
| 77 | of [] -> none |
| 78 | ; [{K, V}] -> {some, V} |
| 79 | end. |
| 80 | |
| 81 | -spec save(ets:tid(), term(), term()) -> |
| 82 | {}. |
| 83 | save(Table, K, V) -> |
| 84 | true = ets:insert(Table, {K, V}), |
| 85 | {}. |