2017年7月5日水曜日

メモリ使用量(使用済み/残メモリ)取得(Swift)

Swiftで使用済みメモリ、残メモリ容量を取得する方法
        
func showMemoryInfo() {
    //使用済みメモリ
    var taskInfo = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size)/4
    var ret: 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)
        }
    }
    let usedMemory = (ret == KERN_SUCCESS ? taskInfo.resident_size as UInt64 : 0)
            
    //フリーメモリ
    var size: mach_msg_type_number_t =
        UInt32(MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size) as mach_msg_type_number_t
    var vmStatInfo = vm_statistics64()
    ret = withUnsafeMutablePointer(to: &vmStatInfo) {
        $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
            host_statistics64(mach_host_self(), host_flavor_t(HOST_VM_INFO64), $0, &size)
        }
    }
    let freeMemory = (ret == KERN_SUCCESS ? vmStatInfo.free_count * 
vm_kernel_page_size : 0)
            
    print("\(usedMemory), \(freeMemory)");

}

0 件のコメント:

コメントを投稿