|
1 | 1 | %% 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. |
2 | 4 | % |
3 | 5 | % get free physical RAM across operating systems |
4 | 6 | % https://docs.oracle.com/en/java/javase/21/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getFreeMemorySize() |
|
7 | 9 | % * freebytes: free physical RAM [bytes] |
8 | 10 | % |
9 | 11 | % 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. |
11 | 20 |
|
12 | 21 | function bytes = ram_free() |
13 | 22 |
|
14 | | -bytes = 0; |
| 23 | +if stdlib.has_java() |
| 24 | + bytes = ram_free_java(); |
| 25 | +elseif stdlib.has_python() |
| 26 | + bytes = py_ram_free(); |
| 27 | +else |
| 28 | + bytes = ram_free_system(); |
| 29 | +end |
15 | 30 |
|
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(); |
| 31 | +bytes = uint64(bytes); |
20 | 32 |
|
21 | | - bytes = m.MemAvailableAllArrays; |
| 33 | +end |
| 34 | + |
| 35 | + |
| 36 | +function bytes = ram_free_system() |
22 | 37 |
|
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) |
30 | | - end |
| 38 | +if ispc() |
| 39 | + cmd = 'pwsh -c "(Get-CimInstance -ClassName CIM_OperatingSystem).FreePhysicalMemory * 1KB"'; |
| 40 | +elseif ismac() |
| 41 | + cmd = 'sysctl -n hw.memsize'; |
| 42 | +else |
| 43 | + cmd = "free -b | awk '/Mem:/ {print $4}'"; |
31 | 44 | end |
32 | 45 |
|
33 | | -bytes = uint64(bytes); |
| 46 | +[s, m] = system(cmd); |
| 47 | +if s == 0 |
| 48 | + bytes = str2double(m); |
| 49 | +end |
34 | 50 |
|
35 | 51 | end |
36 | 52 |
|
|
0 commit comments