c++ - 在 Mac 上检索 RAM 信息?

标签 c++ objective-c c macos

我需要检索系统中存在的 RAM 总量和当前使用的 RAM 总量,以便计算百分比。这类似于:Retrieve system information on MacOS X?

但是,在该问题中,最佳答案建议如何通过读取来获取 RAM:

/usr/bin/vm_stat

由于我的程序的性质,我发现我不是不能从该文件中读取 - 我需要一种方法来为我提供 RAM 信息,而无需简单地打开文件并从中读取。我正在寻找与函数调用有关的东西。最好是这样的:getTotalRam()getRamInUse()

我显然不希望它这么简单,但我一直在寻找除了从文件读取之外的解决方案。

我正在运行 Mac OS X Snow Leopard,但最好能获得一个适用于所有当前 Mac OS X 平台(即 Lion)的解决方案。

解决方案可以使用 C++、C 或 Obj-C,但在我的情况下,C++ 可能是最好的解决方案,因此如果可能,请尝试使用 C++ 提供。

最佳答案

使用 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 统计数据只是稍微有点棘手:

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

然后您可以使用 vmstat 中的数据来获取您想要的信息:

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;

还有一个 64 位版本的界面。

关于c++ - 在 Mac 上检索 RAM 信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8782228/

相关文章:

ios - CoreData iOS App的Sqlite文件位置的位置

c - 使用结构时使用未声明的标识符?

linux - 如何将 bash 脚本中的字符串发送到 c 程序并使用该字符串

c - int_fast8_t和int_fast16_t之间的区别

c++ - OpenGL:渲染超过 8 盏灯,怎么样?

c++ - MinGW 可以毫不费力地复制大多数 unix 系统调用吗?

c++ - 提升 MSM : using state machine itself as implicit top level state

iphone - 如何更改ios分段控件一侧的大小?

objective-c - 如何深度复制 NSIndexPath?

c++ - 将成员函数指针传递给C++中的成员对象