objective-c - 如何像事件监视器一样以编程方式检查 Mac 上的可用系统内存?

标签 objective-c xcode cocoa macos

在 Mac OS X 上,我可以在事件监视器中查看有多少内存可用。我如何以编程方式执行此操作?

最佳答案

这应该可以做到。谷歌搜索结构中字段的确切含义,但从这段代码开始应该是不言自明的。

#import <sys/sysctl.h>
#import <mach/host_info.h>
#import <mach/mach_host.h>
#import <mach/task_info.h>
#import <mach/task.h>
int mib[6]; 
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;

int pagesize;
size_t length;
length = sizeof (pagesize);
if (sysctl (mib, 2, &pagesize, &length, NULL, 0) < 0)
{
    fprintf (stderr, "getting page size");
}

mach_msg_type_number_t count = HOST_VM_INFO_COUNT;

vm_statistics_data_t vmstat;
if (host_statistics (mach_host_self (), HOST_VM_INFO, (host_info_t) &vmstat, &count) != KERN_SUCCESS)
{
    fprintf (stderr, "Failed to get VM statistics.");
}

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;

task_basic_info_64_data_t info;
unsigned size = sizeof (info);
task_info (mach_task_self (), TASK_BASIC_INFO_64, (task_info_t) &info, &size);

double unit = 1024 * 1024;
memLabel.text = [NSString stringWithFormat: @"% 3.1f MB\n% 3.1f MB\n% 3.1f MB", vmstat.free_count * pagesize / unit, (vmstat.free_count + vmstat.inactive_count) * pagesize / unit, info.resident_size / unit];

关于objective-c - 如何像事件监视器一样以编程方式检查 Mac 上的可用系统内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6094444/

相关文章:

用于查找数组最大公共(public)子集的 Objective-C 算法?

objective-c - 下标需要接口(interface) 'NSArray' 的大小,这在非稳定 ABI 中不是常量

c# iPhone 开发 vs objective c iPhone 开发

xcode - 为什么 `ionic run ios`出现 "No matching provisioning profile found"错误?

javascript - 仅在第一个时才考虑动态添加的样式表

objective-c - Mac OS X cocoa 应用程序中的互联网连接通知

java - Objective-C 。你能像 Java 接口(interface)那样使用协议(protocol)吗?

swift - Xcode 11 无法识别核心数据实体

objective-c - 发布键盘事件

ios - 从另一个 View Controller 访问更新的变量值