Programmatically retrieve memory usage on iPhone

前端 未结 9 943
迷失自我
迷失自我 2020-11-22 16:56

I\'m trying to retrieve the amount of memory my iPhone app is using at anytime, programmatically. Yes I\'m aware about ObjectAlloc/Leaks. I\'m not interested in those, only

9条回答
  •  孤城傲影
    2020-11-22 17:33

    Swift 3.1 (As of August 8, 2017)

    func getMemory() {
    
        var taskInfo = mach_task_basic_info()
        var count = mach_msg_type_number_t(MemoryLayout.size)/4
        let kerr: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
            $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
                task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count)
            }
        }
        if kerr == KERN_SUCCESS {
            let usedMegabytes = taskInfo.resident_size/(1024*1024)
            print("used megabytes: \(usedMegabytes)")
        } else {
            print("Error with task_info(): " +
                (String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error"))
        }
    
    }
    

提交回复
热议问题