Memory (macOS): Refines Memory usage detection on macOS to match Activity Monitor more closely

This commit is contained in:
李通洲
2025-12-18 13:36:38 +08:00
parent 716c0e2b5c
commit 610fc2ea36
2 changed files with 14 additions and 16 deletions
+13 -15
View File
@@ -8,27 +8,25 @@
const char* ffDetectMemory(FFMemoryResult* ram)
{
size_t length = sizeof(ram->bytesTotal);
if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, NULL, 0) != 0)
{
if (sysctl((int[]){ CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, NULL, 0) != 0)
return "Failed to read hw.memsize";
}
if (sysctl((int[]){ CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, NULL, 0) != 0)
return "Failed to read hw.memsize";
uint64_t usableMemory = 0;
length = sizeof(usableMemory);
if (sysctlbyname("hw.memsize_usable", &usableMemory, &length, NULL, 0) != 0)
usableMemory = ram->bytesTotal;
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
vm_statistics64_data_t vmstat;
if(host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) (&vmstat), &count) != KERN_SUCCESS)
return "Failed to read host_statistics64";
// https://github.com/exelban/stats/blob/master/Modules/RAM/readers.swift#L56
ram->bytesUsed = ((uint64_t)
+ vmstat.active_count
+ vmstat.inactive_count
+ vmstat.speculative_count
+ vmstat.wire_count
+ vmstat.compressor_page_count
- vmstat.purgeable_count
- vmstat.external_page_count
) * instance.state.platform.sysinfo.pageSize;
uint64_t pageSize = instance.state.platform.sysinfo.pageSize;
uint64_t appMemory = vmstat.internal_page_count * pageSize;
uint64_t wiredMemory = vmstat.wire_count * pageSize;
uint64_t compressed = vmstat.compressor_page_count * pageSize;
uint64_t reserved = ram->bytesTotal - usableMemory;
ram->bytesUsed = appMemory + wiredMemory + compressed + reserved;
return NULL;
}