Skip to content

Commit d98bacc

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

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

Common/Cpp/MemoryUtilization/MemoryUtilization_Mac.tpp

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
#include <mach/mach.h>
1414
#include <mach/mach_host.h>
1515
#include <mach/mach_vm.h>
16-
#include <mach/task_info.h>
1716
#include <mach/vm_statistics.h>
1817

18+
#include "MemoryUtilization.h"
19+
1920
namespace PokemonAutomation{
2021

2122

@@ -93,15 +94,31 @@ MemoryUsage process_memory_usage(){
9394
}
9495
usage.total_system_memory = physical_memory;
9596
{
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;
97+
mach_vm_address_t address = 0;
98+
mach_vm_size_t size = 0;
99+
vm_region_extended_info_data_t info;
100+
mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT;
101+
mach_port_t object_name;
102+
unsigned int pages_resident = 0;
103+
unsigned int pages_swapped_out = 0;
104+
unsigned int pages_dirtied = 0;
105+
106+
while (true) {
107+
auto kr = mach_vm_region(mach_task_self(), &address, &size, VM_REGION_EXTENDED_INFO, (vm_region_info_t)&info, &count, &object_name);
108+
if (kr != KERN_SUCCESS) {
109+
if (kr == KERN_INVALID_ADDRESS) { // end of the address space
110+
break;
111+
}
112+
std::cerr << "mach_vm_region_recurse failed with error: " << mach_error_string(kr) << std::endl;
113+
break;
114+
}
115+
pages_resident += info.pages_resident;
116+
pages_swapped_out += info.pages_swapped_out;
117+
pages_dirtied += info.pages_dirtied;
118+
address += size;
104119
}
120+
usage.process_physical_memory = (size_t)(pages_resident - pages_dirtied) * (size_t)vm_page_size;
121+
usage.process_virtual_memory = usage.process_physical_memory + (size_t)pages_swapped_out * (size_t)vm_page_size;
105122
}
106123
{
107124
vm_statistics_data_t vm_stats;

0 commit comments

Comments
 (0)