Skip to content

Commit 5f260bb

Browse files
committed
use mach_vm_region() to scan for process resident/swapped pages
1 parent b2a9351 commit 5f260bb

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

Common/Cpp/MemoryUtilization/MemoryUtilization_Mac.tpp

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
#include <mach/task_info.h>
1717
#include <mach/vm_statistics.h>
1818

19+
#include "MemoryUtilization.h"
20+
1921
namespace PokemonAutomation{
2022

2123

@@ -93,15 +95,31 @@ MemoryUsage process_memory_usage(){
9395
}
9496
usage.total_system_memory = physical_memory;
9597
{
96-
task_vm_info_data_t tvi;
97-
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
98-
if(KERN_SUCCESS == task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &tvi, &count))
99-
{
100-
usage.process_physical_memory = tvi.resident_size; // resident_size = internal + external + reusable
101-
usage.process_virtual_memory = tvi.virtual_size;
102-
} else {
103-
std::cerr << "Failed to get task info." << std::endl;
98+
mach_vm_address_t address = 0;
99+
mach_vm_size_t size = 0;
100+
vm_region_extended_info_data_t info;
101+
mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
102+
mach_port_t object_name;
103+
unsigned int pages_resident = 0;
104+
unsigned int pages_swapped_out = 0;
105+
unsigned int pages_dirtied = 0;
106+
107+
while (true) {
108+
auto kr = mach_vm_region(mach_task_self(), &address, &size, VM_REGION_EXTENDED_INFO, (vm_region_info_t)&info, &count, &object_name);
109+
if (kr != KERN_SUCCESS) {
110+
if (kr == KERN_INVALID_ADDRESS) { // end of the address space
111+
break;
112+
}
113+
std::cerr << "mach_vm_region_recurse failed with error: " << mach_error_string(kr) << std::endl;
114+
break;
115+
}
116+
pages_resident += info.pages_resident;
117+
pages_swapped_out += info.pages_swapped_out;
118+
pages_dirtied += info.pages_dirtied;
119+
address += size;
104120
}
121+
usage.process_physical_memory = (size_t)(pages_resident - pages_dirtied) * (size_t)vm_page_size;
122+
usage.process_virtual_memory = usage.process_physical_memory + (size_t)pages_swapped_out * (size_t)vm_page_size;
105123
}
106124
{
107125
vm_statistics_data_t vm_stats;

0 commit comments

Comments
 (0)