Как узнать количество доступной RAM памяти в macOS?
Как узнать количество доступной (не всей [Total], а той, что доступна [Available]) RAM памяти в macOS?
Для linux это выглядит так:
#include <fstream>
unsigned long get_mem_total() {
std::string token;
std::ifstream file("/proc/meminfo");
while (file >> token) {
if (token == "MemAvailable:") {
unsigned long mem;
if (file >> mem) {
return mem;
}
else {
return 0;
}
}
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0; // можете кинуть исключение
}
НО! /proc/ нет в macOS...
Желательно проверить свой код перед ответом, т.к. я проверить не смогу - только уже по Feedback пойму.
Ответы (1 шт):
Автор решения: schmidt9
→ Ссылка
Вот пример получения доступной памяти на MacOS
#include <iostream>
#include <mach/mach_host.h>
/**
* Returns free memory in megabytes
* https://gist.github.com/joelrfcosta/5715169
* https://stackoverflow.com/a/8782978/3004003
*/
auto
get_available_ram()
{
// get vmstat
auto count = HOST_VM_INFO_COUNT;
vm_statistics_data_t vmstat;
auto host_port = mach_host_self();
if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vmstat, &count) != KERN_SUCCESS) {
// TODO: handle error
}
// get page size
vm_size_t pagesize;
host_page_size(host_port, &pagesize);
// calculate available RAM
auto mem_free = vmstat.free_count * pagesize;
return mem_free / 1024.0 / 1024.0;
}
Дополнение
64 битная версия
/**
* Warning: may return inconsistent results
* https://stackoverflow.com/questions/14789672/why-does-host-statistics64-return-inconsistent-results
*/
auto
get_available_ram64()
{
// get vmstat
auto count = HOST_VM_INFO_COUNT;
vm_statistics64_data_t vmstat;
auto host_port = mach_host_self();
if (host_statistics64(mach_host_self(), HOST_VM_INFO, (host_info64_t)&vmstat, &count) != KERN_SUCCESS) {
// TODO: handle error
}
// get page size
vm_size_t pagesize;
host_page_size(host_port, &pagesize);
// calculate available RAM
auto mem_free = vmstat.free_count * pagesize;
return mem_free / 1024.0 / 1024.0;
}
int main(int argc, const char * argv[])
{
auto available = get_available_ram();
std::cout << "Available " << available << " MB" << std::endl;
auto available64 = get_available_ram64();
std::cout << "Available64 " << available64 << " MB" << std::endl;
return 0;
}