【问题标题】:Cocoa: How to get current system usage information?Cocoa:如何获取当前系统使用信息?
【发布时间】:2014-04-17 02:58:33
【问题描述】:

如标题所述,如何以编程方式获取 cocoa 中的当前内存使用情况(已使用或空闲...)?

请注意,我需要的是系统的内存使用量,而不仅仅是当前任务。

提前谢谢你!

【问题讨论】:

    标签: macos cocoa memory system


    【解决方案1】:

    您可以像这样获取任务内存使用情况:

    #import <mach/mach.h>
    
    void report_memory(void) {
      struct task_basic_info info;
      mach_msg_type_number_t size = sizeof(info);
      kern_return_t kerr = task_info(mach_task_self(),
                                     TASK_BASIC_INFO,
                                     (task_info_t)&info,
                                     &size);
      if( kerr == KERN_SUCCESS ) {
        NSLog(@"Used memory (in bytes): %u", info.resident_size);
      } else {
        NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
      }
    }
    

    系统内存使用如下:

    #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;
    NSString *results = [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];
    NSLog (@"%@", results);
    

    【讨论】:

    • 不。此函数返回TASK 的内存使用情况,而不是整个系统。这就是我在问题中加入“通知”的原因。
    • 你能解释一下...如何像活动监视器一样计算缓存和应用程序内存?提前致谢
    • 很抱歉我的回复晚了。我没听懂你的问题。
    猜你喜欢
    • 2011-03-07
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    相关资源
    最近更新 更多