gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:21:29 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com