Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple static class to output semi-accurate memory usage and free memory during runtime.
//
// MemoryManager.h
//
// Created by Shilo White on 3/12/12.
// Copyright (c) 2012 Shilocity Productions. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MemoryManager : NSObject
+ (uint)memoryUsageBytes;
+ (float)memoryUsageMegabytes;
+ (uint)memoryFreeBytes;
+ (float)memoryFreeMegabytes;
@end
//
// MemoryManager.m
//
// Created by Shilo White on 3/12/12.
// Copyright (c) 2012 Shilocity Productions. All rights reserved.
//
#import "MemoryManager.h"
#import <mach/mach.h>
#import <mach/mach_host.h>
@implementation MemoryManager
+ (uint)memoryUsageBytes {
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);
return (kerr == KERN_SUCCESS)?info.resident_size:0;
}
+ (float)memoryUsageMegabytes {
return (float)[self memoryUsageBytes]/1048576.0f;
}
+ (uint)memoryFreeBytes {
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;
host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
host_page_size(host_port, &pagesize);
vm_statistics_data_t vm_stat;
if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) return 0;
natural_t mem_free = vm_stat.free_count * pagesize;
return mem_free;
}
+ (float)memoryFreeMegabytes {
return (float)[self memoryFreeBytes]/1048576.0f;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment