Retrieve RAM info on a Mac?

后端 未结 4 2021
悲&欢浪女
悲&欢浪女 2021-02-04 16:53

I need to retrieve the total amount of RAM present in a system and the total RAM currently being used, so I can calculate a percentage. This is similar to: Retrieve system infor

4条回答
  •  花落未央
    2021-02-04 17:23

    Getting the machine's physical memory is simple with sysctl:

    int mib [] = { CTL_HW, HW_MEMSIZE };
    int64_t value = 0;
    size_t length = sizeof(value);
    
    if(-1 == sysctl(mib, 2, &value, &length, NULL, 0))
        // An error occurred
    
    // Physical memory is now in value
    

    VM stats are only slightly trickier:

    mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
    vm_statistics_data_t vmstat;
    if(KERN_SUCCESS != host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmstat, &count))
        // An error occurred
    

    You can then use the data in vmstat to get the information you'd like:

    double total = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count;
    double wired = vmstat.wire_count / total;
    double active = vmstat.active_count / total;
    double inactive = vmstat.inactive_count / total;
    double free = vmstat.free_count / total;
    

    There is also a 64-bit version of the interface.

提交回复
热议问题