Skip to content
This repository was archived by the owner on Nov 17, 2020. It is now read-only.

Commit 579ceb6

Browse files
author
Daniil Fedotov
committed
Cache process memory for 500 ms.
Getting system RSS can take up to hunreds of milliseconds and be not parallelizable on some platforms.
1 parent 3f11e2d commit 579ceb6

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/vm_memory_monitor.erl

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@
5454

5555
-include("rabbit_memory.hrl").
5656

57+
-define(MEM_CACHE_EXP, 500).
58+
5759
%%----------------------------------------------------------------------------
5860

5961
-type vm_memory_high_watermark() :: (float() | {'absolute', integer() | string()}).
@@ -111,17 +113,29 @@ get_memory_limit() ->
111113

112114
get_memory_use(bytes) ->
113115
MemoryLimit = get_memory_limit(),
114-
{get_process_memory(), case MemoryLimit > 0.0 of
116+
{get_process_memory_cached(), case MemoryLimit > 0.0 of
115117
true -> MemoryLimit;
116118
false -> infinity
117119
end};
118120
get_memory_use(ratio) ->
119121
MemoryLimit = get_memory_limit(),
120122
case MemoryLimit > 0.0 of
121-
true -> get_process_memory() / MemoryLimit;
123+
true ->
124+
Cached = get_process_memory_cached(),
125+
Cached / MemoryLimit;
122126
false -> infinity
123127
end.
124128

129+
get_process_memory_cached() ->
130+
Now = time_compat:erlang_system_time(milli_seconds),
131+
case ets:lookup(?MODULE, memory) of
132+
[{memory, Val, ExpTime}] when ExpTime >= Now -> Val;
133+
_ ->
134+
Mem = get_process_memory(),
135+
ets:insert(?MODULE, {memory, Mem, Now + ?MEM_CACHE_EXP}),
136+
Mem
137+
end.
138+
125139
%% Memory reported by erlang:memory(total) is not supposed to
126140
%% be equal to the total size of all pages mapped to the emulator,
127141
%% according to http://erlang.org/doc/man/erlang.html#memory-0
@@ -225,6 +239,7 @@ start_link(MemFraction, AlarmSet, AlarmClear) ->
225239
[MemFraction, {AlarmSet, AlarmClear}], []).
226240

227241
init([MemFraction, AlarmFuns]) ->
242+
ets:new(?MODULE, [named_table, public]),
228243
TRef = erlang:send_after(?DEFAULT_MEMORY_CHECK_INTERVAL, self(), update),
229244
State = #state { timeout = ?DEFAULT_MEMORY_CHECK_INTERVAL,
230245
timer = TRef,

0 commit comments

Comments
 (0)