Skip to content

Commit 6fa189d

Browse files
committed
ram_free: fallbacks
1 parent b77c412 commit 6fa189d

File tree

2 files changed

+35
-14
lines changed

2 files changed

+35
-14
lines changed

+stdlib/private/py_ram_free.m

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
function n = py_ram_free()
2+
3+
try
4+
vm = py.psutil.virtual_memory();
5+
n = uint64(vm.available);
6+
catch
7+
n = 0;
8+
end
9+
10+
end

+stdlib/ram_free.m

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
%% RAM_FREE get free physical RAM
2+
% What "free" memory means has many definitions across computing platforms.
3+
% The user must consider total memory and monitor swap usage.
24
%
35
% get free physical RAM across operating systems
46
% https://docs.oracle.com/en/java/javase/21/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getFreeMemorySize()
@@ -7,26 +9,35 @@
79
% * freebytes: free physical RAM [bytes]
810
%
911
% This is done using Java on non-Windows platforms.
10-
% VisualBasic (needs Windows) is needed to do this with .NET, so we use builtin memory() on Windows.
12+
%
13+
% VisualBasic (needs Windows) is needed to do this with .NET,
14+
%
15+
% builtin memory() on Windows includes swap. The user could do that themselves.
16+
%
17+
% we installed use Java or Python psutil, which are consistent with each other.
18+
%
19+
% Fallback is to shell commands.
1120

1221
function bytes = ram_free()
1322

1423
bytes = 0;
1524

16-
try
17-
% memory() was added cross-platform to Octave ~ 2021.
18-
% Matlab memory() at least through R2025a is still Windows only.
19-
m = memory();
20-
21-
bytes = m.MemAvailableAllArrays;
25+
if stdlib.has_java()
26+
bytes = ram_free_java();
27+
elseif stdlib.has_python()
28+
bytes = py_ram_free();
29+
else
30+
if ispc()
31+
cmd = 'pwsh -c "(Get-CimInstance -ClassName CIM_OperatingSystem).FreePhysicalMemory * 1KB"';
32+
elseif ismac()
33+
cmd = 'sysctl -n hw.memsize';
34+
else
35+
cmd = "free -b | awk '/Mem:/ {print $4}'";
36+
end
2237

23-
catch e
24-
switch e.identifier
25-
case {'MATLAB:memory:unsupported', 'Octave:undefined-function'}
26-
if stdlib.has_java()
27-
bytes = ram_free_java();
28-
end
29-
otherwise, rethrow(e)
38+
[s, m] = system(cmd);
39+
if s == 0
40+
bytes = str2double(m);
3041
end
3142
end
3243

0 commit comments

Comments
 (0)