osx - Cocoa: How to get current system usage information? -
as title described, how can programmatically current memory usage (used or free...) in cocoa?
please notice needs memory usage system instead of current task only.
thank @ advance!
you can task memory usage this:
#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 task_info(): %s", mach_error_string(kerr)); } } and system memory usage this:
#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 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);
Comments
Post a Comment