RAM(Random Access Memory)

Physical memory (RAM) is, along with the CPU, the rarest resource in a system and the one most likely to be contested, and application memory is directly related to performance – often at the expense of other applications. Unlike PC, iOS has no swap space as an alternative resource, which makes memory resources particularly important. In fact, there is a Jetsam mechanism in iOS that handles low RAM events on the system. Jetsam is an out-of-memory (Killer) mechanism similar to Linux.

Memory used by the App

The mach_task_basic_info structure stores the memory usage of a Mach task, where resident_size is the physical memory size used by the application and virtual_size is the virtual memory size.

#define MACH_TASK_BASIC_INFO     20         /* always 64-bit basic info */
struct mach_task_basic_info {
        mach_vm_size_t  virtual_size;       /* virtual memory size (bytes) */
        mach_vm_size_t  resident_size;      /* resident memory size (bytes) */
        mach_vm_size_t  resident_size_max;  /* maximum resident memory size (bytes) */
        time_value_t    user_time;          /* total user run time for
                                               terminated threads */
        time_value_t    system_time;        /* total system run time for
                                               terminated threads */
        policy_t        policy;             /* default policy for new threads */
        integer_t       suspend_count;      /* suspend count for task */
};

Copy the code

The task_info API returns target_task information based on the specified flavor type.

kern_return_t task_info
(
	task_name_t target_task,
	task_flavor_t flavor,
	task_info_t task_info_out,
	mach_msg_type_number_t *task_info_outCnt
);
Copy the code

Get APP memory usage

@return byte */ + (unsigned long long)getAppRAMUsage {struct mach_task_basic_info info; mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; kern_return_t kr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &count); if (kr ! = KERN_SUCCESS) { return 0; } return info.resident_size; }Copy the code

Obtain the total system memory

@return byte */ + (unsigned long long)getSystemRAMTotal {return [NSProcessInfo processInfo].physicalMemory; }Copy the code

Gets the memory usage of the current device

+ (CGFloat)getUsedMemory { size_t length = 0; int mib[6] = {0}; int pagesize = 0; mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; length = sizeof(pagesize); if (sysctl(mib, 2, &pagesize, &length, NULL, 0) < 0) { return 0; } 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) { return 0; } int wireMem = vmstat.wire_count * pagesize; int activeMem = vmstat.active_count * pagesize; return wireMem + activeMem; }Copy the code