DigitalInBlue / Celero

C++ Benchmark Authoring Library/Framework
Other
824 stars 95 forks source link

Memory Measurement on macOS #168

Open jdumas opened 1 year ago

jdumas commented 1 year ago

Feature Request

Hi,

It seems that the functions GetRAMPhysicalUsedByCurrentProcess(), GetRAMVirtualUsedByCurrentProcess() and GetRAMVirtualTotal() are not implemented for macOS platforms. Is this a limitation of macOS, or just a missing feature? If the latter I'd be interested in implementing it, but do you have a unit test/way to measure that the implementation is correct?

DigitalInBlue commented 1 year ago

This is a perfectly doable thing.

Something like:

uint64_t GetRAMPhysicalUsedByCurrentProcess() {
    task_vm_info_data_t vmInfo;
    mach_msg_type_number_t count = TASK_VM_INFO_COUNT;

    if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vmInfo, &count) == KERN_SUCCESS) {
        return vmInfo.phys_footprint;
    }

    return 0;
}
jdumas commented 1 year ago

Thanks! Do you have a similar code for GetRAMVirtualUsedByCurrentProcess()? It seems that's what Celero is currently measuring during testing.

DigitalInBlue commented 1 year ago

Perhaps something like this. You should look at the API to be sure.

#include <iostream>
#include <mach/mach.h>
#include <mach/task_info.h>

uint64_t GetVirtualMemoryUsed() {
    mach_task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
    kern_return_t kr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&taskInfo), &infoCount);

    if (kr != KERN_SUCCESS) {
        std::cerr << "Error: Unable to get task_info. Error code: " << kr << std::endl;
        return 0;
    }

    return taskInfo.virtual_size;
}

int main() {
    uint64_t virtualRAMUsed = GetVirtualMemoryUsed();
    std::cout << "Virtual RAM used by current process: " << virtualRAMUsed << " bytes." << std::endl;

    return 0;
}